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
     
  • 相关阅读:
    sed匹配多行并替换其中的内容
    sysbench 安装、使用和测试
    linux inode号已满的解决办法
    Linux双网卡绑定
    es安装
    kibana安装
    filebeat
    Codeforces 464E The Classic Problem (最短路 + 主席树 + hash)
    Codeforces 1137C Museums Tour (强连通分量, DP)
    HDU 4921 Map(状态压缩)
  • 原文地址:https://www.cnblogs.com/aloneblog/p/6221140.html
Copyright © 2011-2022 走看看