【问题标题】:Python, Limiting search at a specific hyperlink on webpagePython,限制在网页上特定超链接的搜索
【发布时间】:2014-12-23 09:45:57
【问题描述】:

我正在寻找一种通过网页上的超链接下载 .pdf 文件的方法。

向How can i grab pdf links from website with Python script学习,方法是:

import lxml.html, urllib2, urlparse

base_url = 'http://www.renderx.com/demos/examples.html'
res = urllib2.urlopen(base_url)
tree = lxml.html.fromstring(res.read())

ns = {'re': 'http://exslt.org/regular-expressions'}

for node in tree.xpath('//a[re:test(@href, "\.pdf$", "i")]', namespaces=ns):
    print urlparse.urljoin(base_url, node.attrib['href'])

问题是,我怎样才能只在特定的超链接下找到.pdf,而不是列出网页上的所有.pdf?

一种方法是,当它包含某些单词时,我可以限制打印:

If ‘CA-Personal.pdf’ in node:

但是如果 .pdf 文件名发生变化怎么办?或者我只是想限制在网页上的搜索,在“应用程序”的超链接?谢谢。

【问题讨论】:

    标签: python html hyperlink


    【解决方案1】:

    好吧,这不是最好的方法,但没有坏处:

    from bs4 import BeautifulSoup
    import urllib2
    
    domain = 'http://www.renderx.com'    
    url = 'http://www.renderx.com/demos/examples.html'
    
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page.read())
    app = soup.find_all('a', text = "Applications")
    
    for aa in app:
        print domain + aa['href']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多