【问题标题】:why sometimes I get the results but sometimes not even though I run the same code?为什么有时我得到结果但有时即使我运行相同的代码也没有?
【发布时间】:2019-12-29 06:20:29
【问题描述】:

我正在尝试从旅行顾问网站上抓取一些酒店的评论数据。首先,我尝试抓取某家酒店的第一次评论的评论 ID。我运行了我的代码并且可以得到它。但奇怪的是,有时我会收到错误,索引超出范围,即使我运行相同的代码(没有更改我的代码的任何行)。我不是网络抓取专家,但我的猜测是我的代码在我解析页面之前运行。所以我在我的代码中间包含了 time.sleep(n) 但仍然出现同样的问题。有谁知道为什么会这样?下面是我的代码。

import urllib
import time
from urllib import urlopen
from bs4 import BeautifulSoup


page=urlopen("https://www.tripadvisor.com/Hotel_Review-g60878-d13428699-Reviews-Staybridge_Suites_Seattle_Downtown_Lake_Union-Seattle_Washington.html")
soup=BeautifulSoup(page,"html.parser")    
time.sleep(5)

listing=soup.find_all("div", class_="review-container")
review_id=listing[0]["data-reviewid"]
print (review_id)

【问题讨论】:

    标签: python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    您可以尝试首先使用 bs4 然后尝试正则表达式的方法。在对我有用的一系列测试运行中。

    from bs4 import BeautifulSoup
    import requests, re
    
    page= requests.get("https://www.tripadvisor.com/Hotel_Review-g60878-d13428699-Reviews-Staybridge_Suites_Seattle_Downtown_Lake_Union-Seattle_Washington.html")
    p = re.compile(r'id="review_(\d+)')
    soup = BeautifulSoup(page.content, 'lxml')
    ids = [i['data-reviewid'] for i in soup.select('[data-reviewid][class^=hotels-review-list-parts-SingleReview]')]
    if not ids:
        ids = p.findall(page.text)
    print ids
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多