照葫芦画瓢之python爬虫系列----(3)一分钟快速爬取想要的内容


感谢:https://zhuanlan.zhihu.com/p/21255850,提供素材,让我可以照葫芦画瓢


在这里先总结一下爬虫的步骤:

1.确定要爬取的网页源

2.借助集搜客的GMS工作台生成规则

3.编写几行代码,点击开始运行

其实我们的大部分时间是花在生成规则这样的一个步骤上

下载并安装好集搜客,打开ms谋数台,在浏览器中选中要爬取的内容,并为之命名,点击工作台的测试即可看到效果。

照葫芦画瓢之python爬虫系列----(3)一分钟快速爬取想要的内容

然后生成的规则就在数据规则中。

接下来就是编写代码了:

from urllib import request
from lxml import etree
import time

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='forum' and count(./table/tbody/tr[position()>=1 and count(.//*[@class='topic']/a/text())>0])>0]" mode="列表"/>
</列表>
</xsl:template>



<xsl:template match="table/tbody/tr[position()>=1]" mode="list">
<item>
<标题>
<xsl:value-of select="*//*[@class='topic']/a/text()"/>
<xsl:value-of select="*[@class='topic']/a/text()"/>
<xsl:if test="@class='topic'">
<xsl:value-of select="a/text()"/>
</xsl:if>
</标题>
<回复数>
<xsl:value-of select="*//*[@class='replies']/text()"/>
<xsl:value-of select="*[@class='replies']/text()"/>
<xsl:if test="@class='replies'">
<xsl:value-of select="text()"/>
</xsl:if>
</回复数>
</item>
</xsl:template>

<xsl:template match="//*[@id='forum' and count(./table/tbody/tr[position()>=1 and count(.//*[@class='topic']/a/text())>0])>0]" mode="列表">
<item>
<list>
<xsl:apply-templates select="table/tbody/tr[position()>=1]" mode="list"/>
</list>
</item>
</xsl:template>
</xsl:stylesheet>""")

baseurl = "http://www.gooseeker.com/cn/forum/7"
basefilebegin = "jsk_bbs_"
basefileend = ".xml"
count = 1
while (count < 12):
        url = baseurl + "?page=" + str(count)
        conn = request.urlopen(url)
        doc = etree.HTML(conn.read())
        transform = etree.XSLT(xslt_root)
        result_tree = transform(doc)
        print(str(result_tree))
        file_obj = open(basefilebegin+str(count)+basefileend,'w',encoding='UTF-8')
        file_obj.write(str(result_tree))
        file_obj.close()
        count += 1
        time.sleep(2)


因为要爬取的是动态的页面,如果是简单的静态页面,那么直接使用urllib获取html的链接,然后在代入即可。