一般来说,我对python和web抓取还比较陌生。下面的代码可以工作,但是对于实际通过的信息量来说,它似乎非常慢。有什么方法可以轻易地缩短执行时间吗。我不确定,但看起来我打印出来的东西比我实际需要的要难,任何帮助都将不胜感激。在
目前,代码从站点地图开始,然后迭代其他站点地图的列表。在新的sitemaps中,它提取数据信息来构造网页json数据的url。我从json数据中提取一个用于搜索字符串的xml链接。如果找到字符串,它会将其附加到文本文件中。在
#global variable
start = 'https://www.govinfo.gov/wssearch/getContentDetail?packageId='
dash = '-'
urlSitemap="https://www.govinfo.gov/sitemap/PLAW_sitemap_index.xml"
old_xml=requests.get(urlSitemap)
print (old_xml)
new_xml= io.BytesIO(old_xml.content).read()
final_xml=BeautifulSoup(new_xml)
linkToBeFound = final_xml.findAll('loc')
for loc in linkToBeFound:
urlPLmap=loc.text
old_xmlPLmap=requests.get(urlPLmap)
print(old_xmlPLmap)
new_xmlPLmap= io.BytesIO(old_xmlPLmap.content).read()
final_xmlPLmap=BeautifulSoup(new_xmlPLmap)
linkToBeFound2 = final_xmlPLmap.findAll('loc')
for pls in linkToBeFound2:
argh = pls.text.find('PLAW')
theWanted = pls.text[argh:]
thisShallWork =eval(requests.get(start + theWanted).text)
print(requests.get(start + theWanted))
dict1 = (thisShallWork['download'])
finaldict = (dict1['modslink'])[2:]
print(finaldict)
url2='https://' + finaldict
try:
old_xml4=requests.get(url2)
print(old_xml4)
new_xml4= io.BytesIO(old_xml4.content).read()
final_xml4=BeautifulSoup(new_xml4)
references = final_xml4.findAll('identifier',{'type': 'Statute citation'})
for sec in references:
if sec.text == "106 Stat. 4845":
Print(dash * 20)
print(sec.text)
Print(dash * 20)
sec313 = open('sec313info.txt','a')
sec313.write("\n")
sec313.write(pls.text + '\n')
sec313.close()
except:
print('error at: ' + url2)
不知道我为什么花这么长时间在这上面,但我确实做到了。你的代码真的很难看穿。所以我从这个开始,我把它分成两部分,从网站地图上获取链接,然后是其他的东西。我也把一些位分解成不同的函数。 这是检查约2个网址在我的机器上每秒这似乎是正确的。 这样更好(你可以和我争论这个部分)。在
相关问题 更多 >
编程相关推荐