本文實(shí)例講述了Python爬蟲(chóng)框架Scrapy基本用法。分享給大家供大家參考,具體如下:
Xpath
<html><head> <title>標(biāo)題</title></head><body> <h2>二級(jí)標(biāo)題</h2> <p>爬蟲(chóng)1</p> <p>爬蟲(chóng)2</p></body></html>
在上述html代碼中,我要獲取h2的內(nèi)容,我們可以使用以下代碼進(jìn)行獲取:
info = response.xpath("/html/body/h2/text()") 可以看出/html/body/h2為內(nèi)容的層次結(jié)構(gòu),text()則是獲取h2標(biāo)簽的內(nèi)容。//p獲取所有p標(biāo)簽。獲取帶具體屬性的標(biāo)簽://標(biāo)簽[@屬性="屬性值"]
<div class="hide"></div>
獲取class為hide的div標(biāo)簽
div[@class="hide"]
再比如,我們?cè)诠雀鐲hrome瀏覽器上的Console界面使用$x['//h2']命令獲取頁(yè)面中的h2元素信息:
xmlfeed模板
創(chuàng)建一個(gè)xmlfeed模板的爬蟲(chóng)
scrapy genspider -t xmlfeed abc iqianyue.com
核心代碼:
from scrapy.spiders import XMLFeedSpiderclass AbcSpider(XMLFeedSpider): name = 'abc' start_urls = ['http://yum.iqianyue.com/weisuenbook/pyspd/part12/test.xml'] iterator = 'iternodes' # 迭代器,默認(rèn)為iternodes,是一個(gè)基于正則表達(dá)式的高性能迭代器。除了iternodes,還有“html”和“xml” itertag = 'person' # 設(shè)置從哪個(gè)節(jié)點(diǎn)(標(biāo)簽)開(kāi)始迭代 # parse_node會(huì)在節(jié)點(diǎn)與提供的標(biāo)簽名相符時(shí)自動(dòng)調(diào)用 def parse_node(self, response, selector): i = {} xpath = "/person/email/text()" info = selector.xpath(xpath).extract() print(info) return i
csvfeed模板
創(chuàng)建一個(gè)csvfeed模板的爬蟲(chóng)
scrapy genspider -t csvfeed csvspider iqianyue.com
核心代碼
from scrapy.spiders import CSVFeedSpiderclass CsvspiderSpider(CSVFeedSpider): name = 'csvspider' allowed_domains = ['iqianyue.com'] start_urls = ['http://yum.iqianyue.com/weisuenbook/pyspd/part12/mydata.csv'] # headers 主要存放csv文件中包含的用于提取字段的信息列表 headers = ['name', 'sex', 'addr', 'email'] # delimiter 字段之間的間隔 delimiter = ',' def parse_row(self, response, row): i = {} name = row["name"] sex = row["sex"] addr = row["addr"] email = row["email"] print(name,sex,addr,email) #i['url'] = row['url'] #i['name'] = row['name'] #i['description'] = row['description'] return icrawlfeed模板
創(chuàng)建一個(gè)crawlfeed模板的爬蟲(chóng)
scrapy genspider -t crawlfeed crawlspider sohu.com
核心代碼
class CrawlspiderSpider(CrawlSpider): name = 'crawlspider' allowed_domains = ['sohu.com'] start_urls = ['http://sohu.com/'] rules = ( Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True), ) def parse_item(self, response): i = {} #i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract() #i['name'] = response.xpath('//div[@id="name"]').extract() #i['description'] = response.xpath('//div[@id="description"]').extract() return i上面代碼rules部分中的LinkExtractor為連接提取器。
LinkExtractor中對(duì)應(yīng)的參數(shù)及含義
| 參數(shù)名 | 參數(shù)含義 |
|---|---|
| allow | 提取符合正則表達(dá)式的鏈接 |
| deny | 不提取符合正則表達(dá)式的鏈接 |
| restrict_xpaths | 使用XPath表達(dá)式與allow共同作用提取同時(shí)符合對(duì)應(yīng)XPath表達(dá)式和對(duì)應(yīng)正則表達(dá)式的鏈接 |
| allow_domains | 允許提取的域名,比如我們想只提取某個(gè)域名下的鏈接時(shí)會(huì)用到 |
| deny_domains | 進(jìn)制提取的域名 |
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選