我已经用python编写了一个Web抓取程序。它工作正常,但是需要1.5个小时才能执行。我不确定如何优化代码。
该代码的逻辑是每个国家/地区都有许多带有客户名称的ASN。我正在获取所有ASN链接(例如https://ipinfo.io/AS2856)
使用Beautiful汤和正则表达式以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(&)]+)', 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 multiprocessing包来完成。由于多线程程序由于GIL(全局解释器锁定)而无法在python中工作。有关如何执行此操作的示例很多。这里有一些:
Multiprocessing Spider
Speed up Beautiful soup scrapper
关于python - Python Web抓取:执行速度太慢:如何优化速度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54204925/