【发布时间】: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属性的<a>元素时,就会出现该错误。在尝试调用startswith之前,您应该检查该链接是否确实有一个 href。
标签: python web-scraping beautifulsoup web-crawler python-requests