【问题标题】:Web scraper crawler using Breadth First Search in Python在 Python 中使用广度优先搜索的网络爬虫爬虫
【发布时间】: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


【解决方案1】:

您的 href_links 将是 wiki 链接的相对路径。

您必须附加维基百科的 baseUrl。

base_url = 'https://en.wikipedia.org/'

href_links = [base_url + link for link in selector.xpath('//a/@href').getall()]

请注意,如果您在 href 中有外部链接,这将适用于 wiki 链接,请使用如下内容:

href_links = []
for link in selector.xpath('//a/@href').getall():
    if not link.startswith('http'):
        href_links.append(base_url + link)
    else:
        href_links.append(link)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    相关资源
    最近更新 更多