首页 > 解决方案 > 尝试使用 python 和 beautifulsoup 获取 onclick 属性的文本

问题描述

我在网络抓取方面没有很多经验,只是花了几个星期来尝试获取我的代码。我正在尝试从tripadvisor餐厅获取onclick属性中的文本,这很困难。

这是页面中的代码 html

这是我的代码:

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获取全文?...我会很感激你的建议。

标签: python-3.xbeautifulsoup

解决方案


所以去了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:
        ....

推荐阅读