python xpath提取标签内的所有内容(scrapy版本)

解决方案

table_body = html.xpath('/html/body/table[2]/tbody/tr//td')

先获取总的,然后先取含td外表的数据

            keys=r.xpath('text()')
           

在取含标签的数据 

            vs=list(r.xpath('a/text()'))

具体案例:

需求:提取td中的所有内容,但是用text()方法提取不到a标签中的内容。

    def parse2(self,response):
        html = etree.HTML(response.text)
        #绿表格中的内容
        table_body = html.xpath('/html/body/table[2]/tbody/tr//td')  # 获取href中的内容
        for r in table_body:
            keys=r.xpath('text()')
            vs=list(r.xpath('a/text()'))

            if len(vs)>0:
                key=keys[0].replace("'",'')
                v=vs[0]

            else:
                key=keys[0].replace("'",'').split(":")[0]
                v=keys[0].replace("'",'').split(":")[1]

            print((key+'---'+v))

 

 

参考,评论区

https://www.zhihu.com/question/40443483?sort=created

Guess you like

Origin blog.csdn.net/qq_38403590/article/details/119928320
Recommended