【问题标题】:Want to know how to crawling at tripadvisor想知道如何在tripadvisor上爬行
【发布时间】:2021-07-15 18:24:03
【问题描述】:

我正在尝试获取新加坡餐厅的所有 url 链接,但我的代码不起作用

data = requests.get("https://www.tripadvisor.com.sg/Restaurants-g294265-Singapore.html").text

soup = BeautifulSoup(data, "html.parser")

for link in soup.find_all('a', {'property_title'}):
    print('https://www.tripadvisor.com/Restaurant_Review-g294265-' + link.get('href'))
    print(link.string)

在代码soup = BeautifulSoup(data, "html.parser")中不断加载再加载

我不知道为什么会发生这种情况,即使这适用于其他网站。

这是因为旅行顾问阻止抓取还是代码错误?

【问题讨论】:

  • 我在页面上没有看到property_title
  • 你想从网站上抓取什么?

标签: python beautifulsoup web-crawler tripadvisor


【解决方案1】:

它继续加载并再次加载

要获得回复,请添加user-agent header

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}

data = requests.get(
    "https://www.tripadvisor.com.sg/Restaurants-g294265-Singapore.html", headers=headers
).text

但是数据是动态加载的,requests 不支持动态加载页面。但是,网站上提供 JSON 格式的文件,(不清楚你想抓取什么)。要获取所有数据,您可以使用 json/re 模块:

import json
...

data = requests.get(
    "https://www.tripadvisor.com.sg/Restaurants-g294265-Singapore.html", headers=headers
).text

json_data = re.search(r"window\.__WEB_CONTEXT__=({.*});", data, flags=re.MULTILINE).group(1)

print(
    # Prints all the data, you can use `json.loads` instead to access  the data instead
    json.dumps(json_data, indent=4)
)

获取所有链接:

import re
import requests


headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}

data = requests.get(
    "https://www.tripadvisor.com.sg/Restaurants-g294265-Singapore.html", headers=headers
).text

for link in re.findall(r'"detailPageUrl":"(.*?)"', data):
    print("https://www.tripadvisor.com.sg/" + link)

输出(截断):

https://www.tripadvisor.com.sg//Restaurant_Review-g294265-d1145149-Reviews-Grand_Shanghai_Restaurant-Singapore.html
https://www.tripadvisor.com.sg//Restaurant_Review-g294265-d1193730-Reviews-Entre_Nous_creperie-Singapore.html
https://www.tripadvisor.com.sg//Restaurant_Review-g294265-d1173583-Reviews-The_Courtyard-Singapore.html
https://www.tripadvisor.com.sg//Restaurant_Review-g294265-d4611806-Reviews-NOX_Dine_in_the_Dark-Singapore.html
https://www.tripadvisor.com.sg//Restaurant_Review-g294265-d13152787-Reviews-Positano_Risto-Singapore.html

【讨论】:

  • 我想从旅行顾问那里得到的是新加坡餐厅的链接,例如“tripadvisor.com.sg/…
  • 我的主要目的是爬取新加坡所有餐馆的信息来学习python,我只成功获取了一家餐馆的信息而不是全部。这就是为什么我搜索如何获取餐馆的 url,并列出到数组中然后抓取这些的原因
  • @ChoiJaeWon 我已经编辑了我的答案以获取所有链接
  • 哦,引号之间有一个空格!这对我的学习很有帮助。祝你有美好的一天!
猜你喜欢
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 2015-02-19
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多