【问题标题】:Looping through webpages when href does not exist for certain pages当某些页面不存在href时循环浏览网页
【发布时间】:2015-03-19 21:42:16
【问题描述】:

我正在收集来自网络的评论。有些产品有多页评论;其他人只有一页。在这几个人的帮助下,我写了一段代码,基本上可以让爬虫在有“下一页”链接的时候点击。

我的问题是,当只有一页评论时,没有链接可以点击,并且爬虫一直在等待。我希望程序查看下一页链接是否存在:如果存在,请单击它,如果不存在,则返回循环顶部。

这是我的代码:

for url in list_urls:
  while True:
    raw_html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(raw_html)

#See if the "next page" link exists: if it does not, go back to the top of the loop
    href_test = soup.find('div', id='company_reviews_pagination')
    if href_test == None:
       break

#If next-page link exists, click on it
    elif href_test != None:
       last_link = soup.find('div',id='company_reviews_pagination').find_all('a')[-1]
       if last_link.text.startswith('Next'):
          next_url_parts = urllib.parse.urlparse(last_link['href'])
          url = urllib.parse.urlunparse(#code to define the "next-page" url - that part works!)
       else:
          break

到目前为止,它没有给我错误,但程序没有运行,它一直在等待。我究竟做错了什么?我应该尝试使用“try”语句来专门处理此异常吗?

提前非常感谢。非常感谢任何指导。

【问题讨论】:

  • 您能否分享实际的 URL 以便重现问题并帮助您?谢谢。
  • 知道了。没有什么是旧的“尝试/除外”无法解决的。 ;) 感谢@alecxe 愿意提供帮助。

标签: python beautifulsoup href


【解决方案1】:

这就是我修复它的方法。我没有使用“如果链接存在条件”,而是使用了 try/except:

    try:
       last_link = soup.find('div', id='company_reviews_pagination').find_all('a')[-1]
       if last_link.text.startswith('Next'):
         next_url_parts = urllib.parse.urlparse(last_link['href'])
         url = urllib.parse.urlunparse(#code to find the next-page link )

       else:
         break
    except :
       break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多