需求: 获取某网站近10万条数据记录的相关详细信息。
分析:数据的基本信息存放于近1万个页面上,每个页面上10条记录。如果想获取特定数据记录的详细信息,需在基本信息页面上点击相应记录条目,跳转到详细信息页面。详细信息页面的地址可从基本信息页面里的href属性获取。
方法:开始时使用beautiful soup进行爬网,因速度较慢,换用lxml,速度改善不明显。
beautiful soup
import bs4
import re
import requests
import lxml.html
f=open('testpython2.txt','w',encoding='utf-8')
j=30
while(j<41):
beautiful = requests.get(webaddress).content
soup=bs4.BeautifulSoup(beautiful,"lxml")
m=5
while m <85:
daf1=soup.find_all('a')[m].get_text()
if daf1!='哈哈':
daf=soup.find_all('a')[m-1].get('href')
c='webaddress1'+ str(daf)
if requests.get(c).status_code==500:
f.write('Cannot found!')
f.write('\n')
else:
beautiful1=requests.get(c).content
soup1=bs4.BeautifulSoup(beautiful1,"lxml")
daf2=soup1.find(id="project_div2")
p=2
while (p<20):
mm=daf2.find_all('td')[p].get_text()
f.write(mm)
f.write(' ')
p=p+2
daf3=soup1.find(id="xiugai")
hh=0
for tag in daf3(re.compile("td")):
hh=hh+1
q=2
while (q<hh) :
nn=daf3.find_all('td')[q].get_text().replace(' ','')
nn1=daf3.find_all('td')[q+1].get_text().replace(' ','')
nn2=daf3.find_all('td')[q-1].get_text().replace(' ','')
nn3=daf3.find_all('td')[q-2].get_text().replace(' ','')
if nn2==nn3:
f.write(nn2)
f.write(';')
f.write(nn)
f.write(',')
f.write(nn1)
f.write(',')
else:
if nn2=='1':
f.write('InteriorRing ')
f.write(nn2)
f.write(';')
f.write(nn)
f.write(',')
f.write(nn1)
f.write(',')
else:
f.write(nn2)
f.write(';')
f.write(nn)
f.write(',')
f.write(nn1)
f.write(',')
q=q+4
f.write('\n')
m=m+8
j=j+1
f.close()
lxml
import bs4
import re
import requests
import lxml.html
from lxml.cssselect import CSSSelector
f=open('testpython2.txt',encoding='utf-8')
j=2001
while(j<2592):
link="webaddress"
headers={'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6','referer':'link'}
beautiful = requests.get(link,headers=headers).content
tree=lxml.html.fromstring(beautiful)
sel=CSSSelector('div div table tr td a')
results=sel(tree)
m=5
while m <85:
match=results[m]
if results[m-4].text=='XXX:
daf=match.get('href')
c='webaddress2'+ str(daf)
if requests.get(c).status_code==500:
f.write('Cannot found!')
f.write('\n')
else:
beautiful1=requests.get(c).content
tree1=lxml.html.fromstring(beautiful1)
sel1=CSSSelector('div[id="project_div2"] table tr td')
results1=sel1(tree1)
p=2
while (p<20):
match1=results1[p]
mm=match1.text
if mm is None:
f.write('NoValue')
else:
f.write(mm)
f.write(' ')
p=p+2
sel2=CSSSelector('div[id="xiugai"] table tr')
sel3=CSSSelector('div[id="xiugai"] table tr td')
results2=sel2(tree1)
results3=sel3(tree1)
ee=len(results3)
q=2
while (q<ee+1) :
nn1=results3[q].text
nn2=results3[q+1].text
nn3=results3[q-1].text
nn4=results3[q-2].text
f.write(nn4)
f.write(',')
f.write(nn3)
f.write(',')
f.write(nn1)
f.write(',')
f.write(nn2)
f.write(';')
q=q+4
f.write('\n')
m=m+8
j=j+1
f.close()
原文链接:/python/526786.html