【问题标题】:How can i grab pdf links from website with Python script如何使用 Python 脚本从网站获取 pdf 链接
【发布时间】:2011-09-07 13:14:14
【问题描述】:

我经常需要从网站下载 pdf,但有时它们不在一个页面上。 他们在分页中划分了链接,我必须点击每个页面来获取链接。

我正在学习 python,我想编写一些脚本,我可以在其中放置 weburl 并从该 webiste 中提取 pdf 链接。

我是python新手,谁能给我指导一下怎么做

【问题讨论】:

    标签: python web hyperlink


    【解决方案1】:

    urllib2urlparselxml 非常简单。由于您是 Python 新手,所以我对事情的评论更加冗长:

    # modules we're using (you'll need to download lxml)
    import lxml.html, urllib2, urlparse
    
    # the url of the page you want to scrape
    base_url = 'http://www.renderx.com/demos/examples.html'
    
    # fetch the page
    res = urllib2.urlopen(base_url)
    
    # parse the response into an xml tree
    tree = lxml.html.fromstring(res.read())
    
    # construct a namespace dictionary to pass to the xpath() call
    # this lets us use regular expressions in the xpath
    ns = {'re': 'http://exslt.org/regular-expressions'}
    
    # iterate over all <a> tags whose href ends in ".pdf" (case-insensitive)
    for node in tree.xpath('//a[re:test(@href, "\.pdf$", "i")]', namespaces=ns):
    
        # print the href, joining it to the base_url
        print urlparse.urljoin(base_url, node.attrib['href'])
    

    结果:

    http://www.renderx.com/files/demos/examples/Fund.pdf
    http://www.renderx.com/files/demos/examples/FundII.pdf
    http://www.renderx.com/files/demos/examples/FundIII.pdf
    ...
    

    【讨论】:

      【解决方案2】:

      如果有很多带有链接的页面,你可以试试优秀的框架——Scrapy(http://scrapy.org/)。 它很容易理解如何使用它,并且可以下载您需要的pdf文件。

      【讨论】:

        【解决方案3】:

        通过电话,可能不是很可读

        如果您要从网站上获取所有内容,这些内容都是静态页面或其他内容。您可以通过requests

        轻松抓取html
        import requests
        page_content=requests.get(url)
        

        但是如果你抓住一些通讯网站之类的东西。会有一些反掠夺的方法。(如何打破这些嘈杂的东西将是问题)

        • 第一种方式:让您的请求更像浏览器(人类)。 添加标题(您可以使用 Chrome 或 Fiddle 的开发工具复制标题) 制作正确的发布表单。这个应该复制您通过浏览器发布表单的方式。 获取 cookie,并将其添加到请求中

        • 第二种方式。使用硒和浏览器驱动程序。 Selenium 将使用真正的浏览器驱动程序(像我一样,我使用 chromedriver) 记得将 chromedriver 添加到路径中 或者使用代码加载driver.exe 驱动程序=WebDriver.Chrome(路径) 不确定这是设置代码

          driver.get(url) 真正做到通过浏览器浏览网址,降低了抓东西的难度

          获取网页 page=driver.page_sources

          有些网站会跳转几个页面。这会导致一些错误。让您的网站等待某些特定元素的显示。

          尝试: certain_element=ExpectedConditions.presenceOfElementLocated(By.id,'youKnowThereIsAElement'sID) WebDriverWait(certain_element)

          或使用隐式等待:等待你喜欢的时间

        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS)

        您可以通过 WebDriver 控制网站。这里就不赘述了。您可以搜索模块。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-01
          • 1970-01-01
          • 2018-02-10
          • 1970-01-01
          • 2023-03-03
          • 2021-08-19
          相关资源
          最近更新 更多