Python 网页抓取:执行速度太慢:如何优化速度



我用python编写了一个网页抓取程序。它工作正常,但需要 1.5 小时才能执行。我不确定如何优化代码。代码的逻辑是每个国家/地区都有许多带有客户端名称的 ASN。我正在获取所有 ASN 链接(例如 https://ipinfo.io/AS2856)使用 Beautiful soup 和正则表达式将数据作为 JSON 获取。

输出只是一个简单的 JSON。

import urllib.request
import bs4
import re
import json
url = 'https://ipinfo.io/countries'
SITE = 'https://ipinfo.io'

def url_to_soup(url):
   #bgp.he.net is filtered by user-agent
    req = urllib.request.Request(url)
    opener = urllib.request.build_opener()
    html = opener.open(req)
    soup = bs4.BeautifulSoup(html, "html.parser")
    return soup
def find_pages(page):
    pages = []
    for link in page.find_all(href=re.compile('/countries/')):
        pages.append(link.get('href'))
    return pages
def get_each_sites(links):
    mappings = {}
    print("Scraping Pages for ASN Data...")
for link in links:
    country_page = url_to_soup(SITE + link)
    current_country = link.split('/')[2]
    for row in country_page.find_all('tr'):
        columns = row.find_all('td')
        if len(columns) > 0:
            #print(columns)
            current_asn = re.findall(r'd+', columns[0].string)[0]
            print(SITE + '/AS' + current_asn)
            s = str(url_to_soup(SITE + '/AS' + current_asn))
            asn_code, name = re.search(r'(?P<ASN_CODE>ASd+) (?P<NAME>[w.s(&amp;)]+)', s).groups()
            #print(asn_code[2:])
            #print(name)
            country = re.search(r'.*href="/countries.*">(?P<COUNTRY>.*)?</a>', s).group("COUNTRY")
            print(country)
            registry = re.search(r'Registry.*?pb-md-1">(?P<REGISTRY>.*?)</p>', s, re.S).group("REGISTRY").strip()
            #print(registry)
            # flag re.S make the '.' special character match any character at all, including a newline;
            mtch = re.search(r'IP Addresses.*?pb-md-1">(?P<IP>.*?)</p>', s, re.S)
            if mtch:
                ip = mtch.group("IP").strip()
            #print(ip)
            mappings[asn_code[2:]] = {'Country': country,
                                      'Name': name,
                                      'Registry': registry,
                                      'num_ip_addresses': ip}
    return mappings
main_page = url_to_soup(url)
country_links = find_pages(main_page)
#print(country_links)
asn_mappings = get_each_sites(country_links)
print(asn_mappings)

输出符合预期,但速度超慢。

您可能不想加快刮板的速度。当您抓取网站或以人类没有的方式(24/7)连接时,最好将请求保持在最低限度,以便

  • 你混合背景噪音
  • 您不会(D)DoS网站,希望更快地完成,同时为wbesite所有者增加成本

但是,您可以做的是从此站点获取AS名称和编号(请参阅此SO答案),并使用PyASN恢复IP。

我认为您需要的是执行抓取的多个过程。这可以使用 python 多处理包来完成。由于多线程程序在 python 中不起作用,因为 GIL(全局解释器锁)。有很多关于如何做到这一点的例子。以下是一些:

  1. 多处理蜘蛛
  2. 加速美丽的汤刮刀

最新更新