您的位置:首页 > 编程语言 > Python开发

python 爬虫下载链接

2015-10-27 16:28 591 查看
使用python+xpath 获取https://pypi.python.org/pypi/lxml/2.3/的下载链接:

使用requests获取html后,分析html中的标签发现所需要的链接在<table class="list" >...</table> 中
然后分别获却<tr class="odd"> 和<tr class="even">中的内容 ,使用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

经测试,可以正常获取对应的下载链接。作为初学者,代码有很多不当地方,还请大牛审阅之后加以指正。

本文出自 “分享” 博客,请务必保留此出处http://huangfu3342.blog.51cto.com/9181639/1706837
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: