Scrapy是什么苹享?
一個(gè)主流的爬蟲框架
怎么裝阳谍?
pip install scrapy
對于python 3.4以上版本采记,請用
pip3 install scrapy
scrapy 框架會依賴一些其他框架窿春,如安裝過程提示缺少其他框架請自行安裝
動態(tài)網(wǎng)頁是什么拉一?
按F12采盒,Element 和 Source 不一致,Source這個(gè)靜態(tài)頁面是不完整的蔚润。我們需要爬取的內(nèi)容在Soucre頁面找不到
爬取動態(tài)網(wǎng)頁主要有兩種思路:
1. 找到數(shù)據(jù)文件磅氨,如*.json,直接爬取Json文件并解析里面想要的數(shù)據(jù)
2. 調(diào)用瀏覽器執(zhí)行動態(tài)網(wǎng)頁嫡纠,待網(wǎng)頁的動態(tài)加載完成后再像對靜態(tài)網(wǎng)頁那樣進(jìn)行爬取
使用selenium
調(diào)用瀏覽器執(zhí)行動態(tài)頁面需安裝:
pip install selenium
pip install chromedriver_installer
xpath 語法:
self.browser.find_elements_by_xpath
返回所有符合xpath的WebElements
任何一個(gè)WebElement
都可以調(diào)用find_element(s)_by_xxx
烦租, 在xpath表達(dá)式中使用.
約束在當(dāng)前WebElement內(nèi)查找
參考http://www.w3schools.com/xml/xpath_syntax.asp
xp.PNG
WebElement.text
返回文本內(nèi)容
WebElement.getattribute(href)
獲取attribute value
代碼:
import time
from scrapy.spider import Spider
from selenium import webdriver
class LiCaiSpider(Spider):
name = "LiCai"
allowed_domains = ["haohaolicai.com"]
start_urls = [
"https://www.haohaolicai.com/page/borrow/period_profit.jsp?borrowWay=5"
# "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
def __init__(self)
# use any browser you wish
self.browser = webdriver.Chrome() #使用前請安裝對應(yīng)的webdriver
def __del__(self):
self.browser.close()
def parse(self, response):
#start browser
self.browser.get(response.url)
sampleSet = set()
ItemList = self.browser.find_elements_by_xpath('//div[@class="period_model"]/ul')
for item in ItemList:
optText = item.find_element_by_xpath('.//li[@class="period_model_li6"]/a').text
monText = item.find_element_by_xpath('.//li[@class="period_model_li4"]/span').text
if( monText == '6' and optText =='立即投資'):
sampleSet.add(item.find_element_by_xpath('.//li[@class="period_model_li1"]').text)
filename = 'mycrapy'
open(filename, 'w').write(repr(sampleSet))