以前寫的第一份爬取淘寶信息培漏,當(dāng)時覺得還可以趾撵,完全就是一個面向流程的寫法。兢哭〗В》蹬粒現(xiàn)在看來,這是什么鬼篙挽。荆萤。。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from lxml import etree
driver = webdriver.Chrome()
driver.get('https://www.taobao.com')
driver.find_element_by_xpath('//input[@id="q"]').send_keys('Python', Keys.ENTER)
html = driver.page_source
html = etree.HTML(html)
images = html.xpath('//img[@class="J_ItemPic img"]/@data-src')
prices = html.xpath('//div[@class="items"]//strong/text()')
deals = html.xpath('//*[@class="deal-cnt"]/text()')
shops = html.xpath('//*[@class="shopname J_MouseEneterLeave J_ShopInfo"][1]/span[2]/text()')
locations = html.xpath('//div[@class="location"]/text()')
for i in range(len(images)):
items = html.xpath('//*[@class="J_ClickStat"]')[i]
temp = {
'title': items.xpath('string(.)').strip(),
'image': images[i],
'price': prices[i],
'deal': deals[i],
'shop': shops[i],
'location': locations[i],
}
print(temp)
對于標(biāo)題title部分,使用 //*[@class="J_ClickStat"] 定位的是48個元素, 但是直接使用/text()獲取其文本內(nèi)容會得到200多個
在這里采用一種迂回的方法
items = html.xpath('//*[@class="J_ClickStat"]')[i]
items.xpath('string(.)').strip()
先獲取當(dāng)前節(jié)點(diǎn),然后使用 string() 獲取當(dāng)前節(jié)點(diǎn)的所有文本信息,再使用 strip() 函數(shù)去掉所有的空格換行符等