繁体   English   中英

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

[英]Python Web scraping: Too slow in execution: How to Optimize for speed

我用python编写了一个网页抓取程序。 它工作正常,但需要 1.5 小时才能执行。 我不确定如何优化代码。 代码的逻辑是每个国家都有许多带有客户名称的 ASN。 我正在获取所有 ASN 链接(例如https://ipinfo.io/AS2856 ),使用美丽的汤和正则表达式将数据作为 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>AS\d+) (?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)

输出符合预期,但超级慢。

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

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

您可能不想加快刮板速度。 当您抓取一个站点,或以人类不使用的方式(24/7)进行连接时,最好将请求保持在最小值,以便

  • 你融入了背景噪音
  • 你不 (D)DoS 网站希望更快完成,同时为网站所有者增加成本

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM