我经常需要从webistes下载pdf文件,但有时它们不在一页上。 他们分页的链接,我必须点击每一页获取链接。我如何从Python网站抓取网站上的pdf链接
我正在学习python,我想编写一些脚本,我可以把weburl,它从该webiste提取PDF链接。
我新的Python所以任何人都请给我的指导我怎么能做到这一点
我经常需要从webistes下载pdf文件,但有时它们不在一页上。 他们分页的链接,我必须点击每一页获取链接。我如何从Python网站抓取网站上的pdf链接
我正在学习python,我想编写一些脚本,我可以把weburl,它从该webiste提取PDF链接。
我新的Python所以任何人都请给我的指导我怎么能做到这一点
与urllib2
,urlparse
和lxml
很简单。我评论的东西更冗长,因为你是新来的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
...
如果有很多的链接,你可以尝试很好的框架页 - Scrapy(http://scrapy.org/ )。 这是很容易理解如何使用它,并可以下载你需要的PDF文件。
通过电话,也许如果你打算从大网站东西都是静态页面或其他东西是不是很可读
。您可以轻松地请求
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控制网站。这里不会描述。您可以搜索模块。