使用requests获取html后,分析html中的标签发现所需要的链接在
中
然后分别获却 和中的内容 ,使用xpath时可以写成xpath('//table[@class="list"]/tr[@class="even" or "odd"]/td/span/a[1]/@href')
import re
import requests
import urllib2
from lxml import etree
url='https://pypi.python.org/pypi/lxml/2.3/'
head={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36'}
def gethtml(url, *args):
html = requests.get(url, *args).content
return html
def writfile(cont):
try:
fd = open('x.txt', 'w')
try:
fd.write(cont)
finally:
fd.close()
except IOError:
print "file not existing!"
def readfile():
try:
fd = open('x.txt', 'r')
try:
all_the_text = fd.read()
finally:
fd.close()
except IOError:
print "File open error !"
return all_the_text
html = gethtml(url, head)
writfile(html)
all_text = readfile()
dom = etree.HTML(all_text)
url_list = dom.xpath('//table[@class="list"]/tr[@class="even" or "odd"]/td/span/a[1]/@href')
for url in url_list:
print url
经测试,可以正常获取对应的下载链接。作为初学者,代码有很多不当地方,还请大牛审阅之后加以指正。