【问题标题】:How do I make this Web Crawler infinite?如何使这个网络爬虫无限?
【发布时间】:2015-08-18 11:54:51
【问题描述】:

这是我正在尝试编写的代码,(一个循环遍历链接列表的网络爬虫,其中第一个链接是原始链接,然后将网站上的链接附加到列表中,并且 for 循环保持浏览列表,由于某种原因,当添加和打印大约 150 个链接时,脚本会一直停止)

import requests
from bs4 import BeautifulSoup
import urllib.request

links = ['http://example.com']
def spider(max_pages):
    page = 1
    number = 1
    while page <= max_pages:
        try:
            for LINK in links:
                url = LINK
                source_code = requests.get(url)
                plain_text = source_code.text
                soup = BeautifulSoup(plain_text, "html.parser")
                for link in soup.findAll("a"):
                    try:
                        href = link.get("href")
                        if href.startswith("http"):
                            if href not in links:
                                number += 1
                                links.append(href)
                                print("{}: {}".format(number, href))
                    except:
                        pass

        except Exception as e:
            print(e)

while True:
    spider(10000)

我该怎么做才能让它无限?

【问题讨论】:

  • 尝试打印出异常而不是忽略它们,我的猜测是循环的大多数迭代都会导致错误
  • 也许您的代码运行良好,而网站只有 150 个页面。
  • 我脸红了,但这么多链接(将近 200 个)不会也链接到更多吗?
  • 我添加了一个“except Exception as e: print(e)”并返回“'NoneType' object has no attribute 'startswith'”,所以显然其中一个字符串不像一个,还是我错了?我该如何解决这个问题?
  • 当您找到一个没有 href 属性的 &lt;a&gt; 元素时,就会出现该错误。在尝试调用 startswith 之前,您应该检查该链接是否确实有一个 href。

标签: python web-scraping beautifulsoup web-crawler python-requests


【解决方案1】:

当您发现没有href 属性的&lt;a&gt; 元素时,就会出现该错误。在尝试调用startswith之前,您应该检查该链接是否真的有一个href。

【讨论】:

  • 谢谢凯文,非常感谢! :)
【解决方案2】:

萨米尔·查欣,

你的代码失败了,因为 href 变量在

中没有
href = link.get("href")

所以把另一张支票放在那里:

if (href is not none) and href.startswith("http://")

请转换python代码中的逻辑

    try to debug using print statement like :



href = link.get("href")
                        print("href "+ href)
                        if href is not none and href.startswith("http"):
                            print("Condition passed 1")
                            if href not in links:
                                print("Condition passed 2")
                                number += 1
                                links.append(href)
                                print("{}: {}".format(number, href))

【讨论】:

  • 有时我得到“('Connection aborted.', gaierror(11001, 'getaddrinfo failed'))”,为什么?
  • 我将您的代码添加到我的程序中,现在它根本不打印任何东西?
  • 尝试使用 print 语句进行调试,例如: href = link.get("href") print("href "+ href) if href 不是 none 和 href.startswith("http"): print ("条件通过 1") if href 不在链接中: print("条件通过 2") number += 1 links.append(href) print("{}: {}".format(number, href))跨度>
  • 对于那个错误你可以检查这个链接:docs.python.org/2/library/socket.html#socket.gaierror
  • 当服务器无法访问时,就会出现这种类型的错误。你需要捕捉那些错误。您可以通过打印给您错误的链接来验证,然后使用浏览器点击该链接。我希望浏览器也会显示一些错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 2011-10-17
  • 1970-01-01
相关资源
最近更新 更多