zoukankan      html  css  js  c++  java
  • 使用python+xpath 获取https://pypi.python.org/pypi/lxml/2.3/的下载链接

    使用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
     
  • 相关阅读:
    第二周作业
    第二次作业
    第一周作业
    我的2018年终总结
    css总结
    python中使用selenium错误-Firefox浏览器
    postman中 form-data、x-www-form-urlencoded、raw、binary的区别
    谷歌地图API(一)
    2014新年开题
    图书馆管理系统-需求分析
  • 原文地址:https://www.cnblogs.com/aloneblog/p/6221140.html
Copyright © 2011-2022 走看看