python-3.x - 尝试使用 python 和 beautifulsoup 获取 onclick 属性的文本
问题描述
我在网络抓取方面没有很多经验,只是花了几个星期来尝试获取我的代码。我正在尝试从tripadvisor餐厅获取onclick属性中的文本,这很困难。
这是我的代码:
with requests.Session() as s:
for offset in range (1,2):
url = f'https://www.tripadvisor.fr/Restaurant_Review-g187147-d17452512-Reviews or {offset}-Madame_Pop_s-Paris_Ile_de_France.html'
r = s.get(url)
soup = bs(r.content, 'lxml')
if not offset:
inf_rest_name = soup.select_one('.heading').text.replace("\n","").strip()
rest_eclf = soup.select_one('.header_links a').text.strip()
for review in soup.select('.reviewSelector'):
name_client = review.select_one('.info_text > div:first-child').text.strip()
date_rev_cl = review.select_one('.ratingDate')['title'].strip()
titre_rev_cl = review.select_one('.noQuotes').text.replace(",","").strip()
opinion_cl= review.select_one('.partial_entry').text.replace("\n","").strip()
for opplus in opinion_cl:
secondtag = opplus.select_one('span', {'onclick':'widgetEvCall('handlers.clickExpand',event,this);'})
row = [f"{inf_rest_name}", f"{rest_eclf}", f"{name_client}", f"{date_rev_cl}", f"{titre_rev_cl}", f"{opinion_cl}"]
w.writerow(row)
在最后一部分中,对于 opplus... 的介绍给了我一个错误。我还尝试在“.partial_entry”旁边的第 13 行“.onclick”上键入,但它不起作用。你能告诉我我需要改变什么吗?...我该怎么做才能用python获取全文?...我会很感激你的建议。
解决方案
所以去了tripadvisor网站,看到当你点击“加号”时,它会向tripadvisor发送发布请求。基本上你需要做的是去网络并弄清楚网站的行为方式。
由于我有一些空闲时间,我决定帮助你。
with requests.Session() as s:
for offset in range (1,2):
url = f'https://www.tripadvisor.fr/Restaurant_Review-g187147-d17452512-Reviews or {offset}-Madame_Pop_s-Paris_Ile_de_France.html'
r = s.get(url)
soup = bs(r.content, 'lxml')
# Now the trick is that there is ajax that sends post request to https://www.tripadvisor.fr/OverlayWidgetAjax?Mode=EXPANDED_HOTEL_REVIEWS_RESP&metaReferer=
# The data that it sends contain review ids, plus you need to send in headers Referer
# First get the list of ids
reviews = soup.select('.reviewSelector')
ids = [review.get('data-reviewid') for review in reviews]
# Now send request
req = s.post(
'https://www.tripadvisor.fr/OverlayWidgetAjax?Mode=EXPANDED_HOTEL_REVIEWS_RESP&metaReferer=',
data={'reviews': ','.join(ids), 'contextChoice': 'DETAIL'},
headers = {'Referer': req.url}
)
# And now you can follow the logic that you had
soup = bs(req.content, 'lxml')
if not offset:
....
推荐阅读
- spring-integration - spring integration dsl聚合器不发布消息
- maven - 无法解决 Gradle 中的 rar 依赖项
- java - 即使我有 JScrollPane 也没有显示 JTable 列标题
- javascript - 从装饰器调用带有命名参数的 Typescript 方法
- c# - 测试超时时在 nunit 中重试不起作用
- javascript - 如何将变量传递给我的回调函数或类似函数
- dart - firebase 监听中的 for 循环没有更新
- java - 如何为使用 Hibernate 并在 NetBeans 中开发的 Apache Derby 数据库应用程序构建可执行 jar 文件?
- javascript - javascript:使用复杂对象中的关联数组
- android - EditText 居中内容的问题,如果有重力,软键盘会覆盖它