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
使用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
相关文章推荐
- python迭代器
- Python 查看文件的读写权限
- python基础-特性
- python 入门笔记(二)
- python数据库操作常用功能使用详解(创建表/插入数据/获取数据)
- python数据库操作常用功能使用详解(创建表/插入数据/获取数据)
- Python操作Reids之任务队列
- python列表生成
- python迭代
- Python 如何遍历文件夹以及子文件夹下的所有文件
- ubuntu python 2.7 升级到 3.3
- Python + Selenium网页自动化测试
- python函数
- macosx 10.11 python pip install 出现错误OSError: [Errno 1] Operation not permitted:
- Python 2.7 mysql-python(MySQLdb) win7 64bit 扩展安装
- python 入门笔记(一)
- python使用wmi模块获取windows下的系统信息 监控系统
- 初探oVirt-体验sdk-python
- python内建函数——字符串处理
- Python中使用tarfile压缩、解压tar归档文件示例