Tej*_*gut 5 web-crawler python-3.x
我一直在为初学者观看python上的bucky roberts视频,并且我正在尝试使用视频中的类似代码为Wikipedia页面构建基本的网络抓取工具。
import requests
from bs4 import BeautifulSoup
def main_page_spider(max_pages):
page_list={1: "Contents",
2:"Overview",
3:"Outlines",
4:"Lists",
5:"Portals",
6:"Glossaries",
7:"Categories",
8:"Indices",
9:"Reference",
10:"Culture",
11:"Geography",
12:"Health",
13:"History",
14:"Mathematics",
15:"Nature",
16:"People",
17:"Philosophy",
18:"Religion",
19:"Society",
20:"Technology"}
for page in range(1,max_pages+1):
if page == 1:
url = "https://en.wikipedia.org/wiki/Portal:Contents"
else:
url = "https://en.wikipedia.org/wiki/Portal:Contents/" + str(page_list[page])
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
divs = soup.find('div', {'class': "mw-body-content", 'id': "bodyContent"})
for link in divs.findAll('a'):
href = "https://en.wikipedia.org" + str(link.get("href"))
get_link_data(href)
print(href)
def get_link_data(link_url):
source_code = requests.get(link_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
divs = soup.find('div',{'class': "mw-body-content", 'id': "bodyContent"})
for link in divs.findAll('a'):
link_href_data = link.get("href")
print(link_href_data)
main_page_spider(3)
Run Code Online (Sandbox Code Playgroud)
问题是当我注释掉get_link_data()该程序的函数调用时,工作正常,并且从定义的页面数中获取了所有链接。但是,当我取消注释时,程序会收集很少的链接,并给我类似的错误
socket.gaierror,urllib3.exceptions.NewConnectionError,urllib3.exceptions.MaxRetryError,requests.exceptions.ConnectionError
我该如何解决?
任何时候您进行抓取时都应该引入延迟,以免淹没网站的资源 - 或您自己的资源。正如您所描述的,运行注释掉该get_link_data行的脚本会产生 2763 行输出。您将尽快抓取 2763 个 URL。这通常会触发错误,要么来自限制您的站点,要么来自您自己的网络,或者您的 DNS 服务器被堵塞。
在每次调用之前添加延迟get_link_data- 我建议至少一秒钟。这需要一段时间,但请记住 - 您正在从免费资源中收集数据。不要滥用它。
您还应该对您关注的链接更有选择性。在 2763 个 URL 输出中,只有 2291 个唯一的 URL,这相当于您需要抓取两次的近 500 个页面。跟踪您已经处理过的 URL,并且不要再次请求它们。
您可以进一步细化这一点 - 大约 100 个 URL 包含片段( 后面的部分#)。当像这样抓取时,片段通常应该被忽略 - 它们通常只引导浏览器聚焦的地方。如果您#从每个 URL 中删除 及其后面的所有内容,您将剩下 2189 个唯一页面。
您提供的一些链接也格式错误。他们看起来像这样:
https://en.wikipedia.org//en.wikipedia.org/w/index.php?title=Portal:Contents/Outlines/Society_and_social_sciences&action=edit
Run Code Online (Sandbox Code Playgroud)
您可能想要修复这些问题 - 甚至可能完全跳过“编辑”链接。
最后,即使您做了所有这些事情,您也可能会遇到一些异常。互联网是一个混乱的地方:)所以你需要包含错误处理。沿着这些思路:
for link in divs.findAll('a'):
href = "https://en.wikipedia.org" + str(link.get("href"))
time.sleep(1)
try:
get_link_data(href)
except Exception as e:
print("Failed to get url {}\nError: {}".format(href, e.__class__.__name__)
Run Code Online (Sandbox Code Playgroud)
````
| 归档时间: |
|
| 查看次数: |
208 次 |
| 最近记录: |