Ony*_*Lam 2 python scrapy web-scraping
我是Python的新手,我正在尝试使用scrapy下载并保存本网站的pdf文件:http: //www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#中文译名
以下是我的代码:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
class legco(BaseSpider):
name = "legco"
allowed_domains = ["http://www.legco.gov.hk/"]
start_urls = ["http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard"]
rules =(
Rule(SgmlLinkExtractor(allow=r"\.pdf"), callback="save_pdf")
)
def parse_listing(self, response):
hxs = HtmlXPathSelector(response)
pdf_urls=hxs.select("a/@href").extract()
for url in pdf_urls:
yield Request(url, callback=self.save_pdf)
def save_pdf(self, response):
path = self.get_path(response.url)
with open(path, "wb") as f:
f.write(response.body)
Run Code Online (Sandbox Code Playgroud)
基本上我试图将搜索限制为只与".pdf"链接,然后选择"a/@ hfref".
从输出,我看到这个错误:
2015-03-09 11:00:22-0700 [legco]错误:蜘蛛错误处理http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard>
任何人都可以建议我如何修复我的代码?非常感谢!
首先,如果你想要工作,你需要使用aCrawlSpiderrules.此外,rules应该定义为可迭代的,通常它是一个元组(缺少逗号).
无论如何,我不是采用这种方法,而是BaseSpider在链接上使用正常的循环并检查href结束.pdf,然后在回调中将pdf保存到文件中:
import urlparse
from scrapy.http import Request
from scrapy.spider import BaseSpider
class legco(BaseSpider):
name = "legco"
allowed_domains = ["www.legco.gov.hk"]
start_urls = ["http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard"]
def parse(self, response):
base_url = 'http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/'
for a in response.xpath('//a[@href]/@href'):
link = a.extract()
if link.endswith('.pdf'):
link = urlparse.urljoin(base_url, link)
yield Request(link, callback=self.save_pdf)
def save_pdf(self, response):
path = response.url.split('/')[-1]
with open(path, 'wb') as f:
f.write(response.body)
Run Code Online (Sandbox Code Playgroud)
(为我工作)
| 归档时间: |
|
| 查看次数: |
2345 次 |
| 最近记录: |