【问题标题】:Web crawling URLs and their URLs recursively递归地抓取 URL 及其 URL
【发布时间】:2020-03-09 11:14:20
【问题描述】:

所以几天来我一直在努力编写这个网络爬虫,但我不知道如何让它工作。我一直在寻找类似的问题和解决方案,但我找不到任何东西,所以如果已经问过这个问题,请参考另一个问题。

我的网络爬虫应该找到第一个网站链接到的 n 个 url,然后找到这些 n 个 url 所在的 x 个 url链接到等等,直到达到一定的深度,并且每个级别都有一定数量的 url。例如 - 我输入了一个我想抓取的 URL,我找到了 3 个链接 URL,3 个 URL 链接到这 3 个 URL 中的每一个,等等。 1+3^1+3^2+3^4... 网址。到目前为止,我已经写了这个,但我无法让它按我的意愿工作。

from bs4 import BeautifulSoup
import requests

url = 'http://www.baidu.com'
depth = 3 #3 levels
count = 3 #amount of urls in each level

def extractURL(url, depth, count):
  list = []
  response = requests.get(url)
  soup = BeautifulSoup(response.text, 'lxml')
  tags = soup.find_all('a')
  newtags = tags[:depth]
  for link in newtags:
      url2 = link.get('href')
      if url2 is not None and url2.startswith("http"):
          list.append(url2)
  for url3 in list:
      if(count > 0):
          if not url3 is None and "http" in url:
             print(url, "->", url3)
             count = count-1
             print("----------------") #divider for each url and connecting urls..?
             extractURL(url3, depth, count)

extractURL(url, depth, count)
print("Done")

关键是要打印“url ->(链接到)url2”。我认为我的计数器无法正常工作,因为它永远不会重置,但我不知道如何解决这个问题。提前致谢!

【问题讨论】:

  • 尝试从函数参数中删除计数,然后在函数的第一行添加global count

标签: python python-3.x beautifulsoup web-crawler


【解决方案1】:

您可以使用此代码适当地提取链接。 您必须将每一层链接分开,以消除重复的链接分析

from bs4 import BeautifulSoup
import requests

url = 'http://www.baidu.com'
depth = 3  # 3 levels
count = 3  # amount of urls in each level
url_list_depth = [[] for i in range(0, depth + 1)]
url_list_depth[0].append(url)
for depth_i in range(0, depth):
    for links in url_list_depth[depth_i]:
        response = requests.get(links)
        soup = BeautifulSoup(response.text, 'html.parser')
        tags = soup.find_all('a')
        for link in tags:
            url_new = link.get('href')
            flag = False
            for item in url_list_depth:
                for l in item:
                    if url_new == l:
                        flag = True

            if url_new is not None and "http" in url_new and flag is False:
                url_list_depth[depth_i + 1].append(url_new)
                print(links, "->", url_new)

print('Done')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2017-07-07
    相关资源
    最近更新 更多