【发布时间】:2019-01-15 18:33:56
【问题描述】:
我用 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>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版本。 Python2.7 和 Python3 为您的案例提供了非常不同的工具
-
print(asn_mappings)- python 3.x ?究竟是哪个版本? -
python 3.7.0 ,解析一个页面需要几秒钟
-
代码在另一台机器上运行了 2 小时。我不知道是内存问题还是网速问题。
标签: python web-scraping