Python爬蟲框架Scrapy基本用法入門教程
本文實例講述了Python爬蟲框架Scrapy基本用法。分享給大家供大家參考,具體如下:
Xpath
<html> <head> <title>標題</title> </head> <body> <h2>二級標題</h2> <p>爬蟲1</p> <p>爬蟲2</p> </body> </html>
在上述html代碼中,我要獲取h2的內容,我們可以使用以下代碼進行獲?。?/p>
info = response.xpath("/html/body/h2/text()")
可以看出/html/body/h2為內容的層次結構,text()則是獲取h2標簽的內容。//p獲取所有p標簽。獲取帶具體屬性的標簽://標簽[@屬性="屬性值"]
<div class="hide"></div>
獲取class為hide的div標簽
div[@class="hide"]
再比如,我們在谷歌Chrome瀏覽器上的Console界面使用$x['//h2']命令獲取頁面中的h2元素信息:

xmlfeed模板
創(chuàng)建一個xmlfeed模板的爬蟲
scrapy genspider -t xmlfeed abc iqianyue.com
核心代碼:
from scrapy.spiders import XMLFeedSpider
class AbcSpider(XMLFeedSpider):
name = 'abc'
start_urls = ['http://yum.iqianyue.com/weisuenbook/pyspd/part12/test.xml']
iterator = 'iternodes' # 迭代器,默認為iternodes,是一個基于正則表達式的高性能迭代器。除了iternodes,還有“html”和“xml”
itertag = 'person' # 設置從哪個節(jié)點(標簽)開始迭代
# parse_node會在節(jié)點與提供的標簽名相符時自動調用
def parse_node(self, response, selector):
i = {}
xpath = "/person/email/text()"
info = selector.xpath(xpath).extract()
print(info)
return i
csvfeed模板
創(chuàng)建一個csvfeed模板的爬蟲
scrapy genspider -t csvfeed csvspider iqianyue.com
核心代碼
from scrapy.spiders import CSVFeedSpider
class 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 i
crawlfeed模板
創(chuàng)建一個crawlfeed模板的爬蟲
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中對應的參數及含義
| 參數名 | 參數含義 |
|---|---|
| allow | 提取符合正則表達式的鏈接 |
| deny | 不提取符合正則表達式的鏈接 |
| restrict_xpaths | 使用XPath表達式與allow共同作用提取同時符合對應XPath表達式和對應正則表達式的鏈接 |
| allow_domains | 允許提取的域名,比如我們想只提取某個域名下的鏈接時會用到 |
| deny_domains | 進制提取的域名 |
更多關于Python相關內容可查看本站專題:《Python Socket編程技巧總結》、《Python正則表達式用法總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python?PyJWT庫簡化JSON?Web?Token的生成與驗證
PyJWT庫為Python開發(fā)者提供了簡便的生成和驗證JWT的工具,本文將深入介紹PyJWT庫的核心概念、功能以及實際應用,通過豐富的示例代碼,幫助大家更全面地了解和應用這一強大的JWT庫2023-12-12
Python使用smtplib模塊發(fā)送電子郵件的流程詳解
Python中自帶的smtplib模塊可以進行基于SMTP協議的郵件操作,這里我們便總結了Python使用smtplib模塊發(fā)送電子郵件的流程詳解,并對一些常見的問題給出了解決方法:2016-06-06

