时间:2021-07-01 10:21:17 帮助过:16人阅读

第一步:利用集搜客谋数台的直观标注功能,可以极快速度自动生成一个调试好的抓取规则,其实是一个标准的xslt程序,如下图,把生成的xslt程序拷贝到下面的程序中即可。注意:本文只是记录实验过程,实际系统中,将采用多种方式把xslt程序注入到内容提取器重。

第二步:执行如下代码(在windows10, python3.2下测试通过),请注意:xslt是一个比较长的字符串,如果删除这个字符串,代码没有几行,足以见得Python之强大
#/usr/bin/python
from urllib import request
from lxml import etree
from selenium import webdriver
import time
# 京东手机商品页面
url = "http://item.jd.com/1312640.html"
# 下面的xslt是通过集搜客的谋数台图形界面自动生成的
xslt_root = etree.XML("""\
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="/">
<商品>
<xsl:apply-templates select="//*[@id='itemInfo' and count(.//*[@id='summary-price']/div[position()=2]/strong/text())>0 and count(.//*[@id='name']/h1/text())>0]" mode="商品"/>
</商品>
</xsl:template>
<xsl:template match="//*[@id='itemInfo' and count(.//*[@id='summary-price']/div[position()=2]/strong/text())>0 and count(.//*[@id='name']/h1/text())>0]" mode="商品">
<item>
<价格>
<xsl:value-of select="*//*[@id='summary-price']/div[position()=2]/strong/text()"/>
<xsl:value-of select="*[@id='summary-price']/div[position()=2]/strong/text()"/>
<xsl:if test="@id='summary-price'">
<xsl:value-of select="div[position()=2]/strong/text()"/>
</xsl:if>
</价格>
<名称>
<xsl:value-of select="*//*[@id='name']/h1/text()"/>
<xsl:value-of select="*[@id='name']/h1/text()"/>
<xsl:if test="@id='name'">
<xsl:value-of select="h1/text()"/>
</xsl:if>
</名称>
</item>
</xsl:template>
</xsl:stylesheet>""")
# 使用webdriver.PhantomJS
browser = webdriver.PhantomJS(executable_path='C:\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe')
browser.get(url)
time.sleep(3)
transform = etree.XSLT(xslt_root)
# 执行js得到整个dom
html = browser.execute_script("return document.documentElement.outerHTML")
doc = etree.HTML(html)
# 用xslt从dom中提取需要的字段
result_tree = transform(doc)
print(result_tree)第三步:下图可以看到,网页中的手机名称和价格被正确抓取下来了