【发布时间】:2021-03-16 15:57:38
【问题描述】:
我想为维基百科页面创建网络爬虫(页面内的所有链接也被打开并保存),这需要以广度优先搜索方式实现。我一直在查看很多来源和 stackoverflow 代码/问题,但无法实现它。 我尝试了以下代码:
import requests
from parsel import Selector
import time
start = time.time()
### Crawling to the website fetch links and images -> store images -> crawl more to the fetched links and scrape more images
all_images = {} # website links as "keys" and images link as "values"
# GET request to recurship site
response = requests.get('https://en.wikipedia.org/wiki/Plant')
selector = Selector(response.text)
href_links = selector.xpath('//a/@href').getall()
image_links = selector.xpath('//img/@src').getall()
for link in href_links:
try:
response = requests.get(link)
if response.status_code == 200:
image_links = selector.xpath('//img/@src').getall()
all_images[link] = image_links
except Exception as exp:
print('Error navigating to link : ', link)
print(all_images)
end = time.time()
print("Time taken in seconds : ", (end-start))
但这会引发错误,提示“导航到链接时出错”。我该怎么做?我是这个领域的新手。
【问题讨论】:
-
在这些情况下打印错误异常总是好的。
print(exp)
标签: python-3.x web-scraping nlp