2011-06-03 120 views
2

我經常需要從webistes下載pdf文件,但有時它們不在一頁上。 他們分頁的鏈接,我必須點擊每一頁獲取鏈接。我如何從Python網站抓取網站上的pdf鏈接

我正在學習python,我想編寫一些腳本,我可以把weburl,它從該webiste提取PDF鏈接。

我新的Python所以任何人都請給我的指導我怎麼能做到這一點

回答

7

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 
... 
0

如果有很多的鏈接,你可以嘗試很好的框架頁 - Scrapy(http://scrapy.org/ )。 這是很容易理解如何使用它,並可以下載你需要的PDF文件。

0

通過電話,也許如果你打算從大網站東西都是靜態頁面或其他東西是不是很可讀

。您可以輕鬆地請求

import requests 
page_content=requests.get(url) 

搶HTML,但如果你抓住像一些通訊網站的事情。會有一些抗掠方式(如何打破這些嘈雜的東西會是問題)

  • 弗里斯特方式:讓您的要求更像是一個瀏覽器(人)。 添加標題(您可以使用Chrome或Fiddle的開發工具來複制標題) 可以創建正確的發佈表單。此應該複製您通過瀏覽器發佈表單的方式。 獲取cookies,並將其添加到請求中

  • 第二種方式。使用硒和瀏覽器驅動程序。硒將使用真正的瀏覽器驅動器(像我一樣,我使用chromedriver) remeber到chromedriver的路徑添加到 還是用代碼加載driver.exe 司機= WebDriver.Chrome(路徑) 不知道是這一套達代碼

    driver.get(URL) 它真實地遨遊瀏覽器通過該URL,所以它會降低掠東西

    得到 網頁頁面的難度= driver.page_soruces

    一些網站會跳幾頁。這會導致一些錯誤。讓您的網站等待某些元素顯示。

    嘗試: certain_element = ExpectedConditions.presenceOfElementLocated(By。ID,'youKnowThereIsAElement'sID) WebDriverWait(certain_element)

    ,或者使用隱式的等待:。等你喜歡

driver.manage()的時間超時()implicitlyWait(5,TimeUnit.SECONDS )

你可以通過WebDriver控制網站。這裏不會描述。您可以搜索模塊。