跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • 请教 Python 中 xpath 如何实现这种需求
未分類
25 3 月 2021

请教 Python 中 xpath 如何实现这种需求

请教 Python 中 xpath 如何实现这种需求

資深大佬 : 2bin 1

如下,我想获取 a 标签下的文本,aaabbbccc 作为列表一个值,而不是[“aaa”,”bbb”,”ccc”],该如何处理呢?

from lxml import etree  html_str=''' <span class="til">     <a href="http://www.xxxx.com">         "aaa"         <br>         "bbb"         "ccc"         <br>     </a> </span> '''  html = etree.HTML(html_str) content = html.xpath('//a/text()') print(content)  """ output: ['n        "aaa"n        ', 'n        "bbb"n        "ccc"n        ', 'n    '] """ 

大佬有話說 (12)

  • 資深大佬 : ch2

    改用 BeautifulSoup,取 node.text

  • 資深大佬 : QuinceyWu

    price = [x.strip() for x in content if x.strip() != ”]
    str1 = price[1].replace(” “, “”).replace(“n”, ”).replace(‘”‘, “”)
    str2 = price[0].replace(‘”‘, ”)
    print(str2+str1)

  • 資深大佬 : meiyoumingzi6

    列表都拿到了, 拼起来不就好了?

  • 資深大佬 : mekingname

    content = ”.join(x.strip() for x in html.xpath(‘//a/text()’))

  • 資深大佬 : polarpy

    拿出来的值替换换行跟空格

  • 資深大佬 : mrleohe

    ”.join([i.strip() for i in ”.join(html.xpath(‘//a/text()’)).split(‘”‘) ])

  • 資深大佬 : CLCLCLCLCL

    html = etree.HTML(html_str)
    content = html.xpath(‘string(//a)’)

    直接用 string 就行

  • 主 資深大佬 : 2bin

    @CLCLCLCLCL 试了下,貌似只能提取第一个 a 标签的,有多个 a 后面不知道怎么提取出来

  • 資深大佬 : zyb201314

    #这样?
    html = etree.HTML(html_str)
    lst=[]
    for a in html.xpath(‘//span//a’):
    content = a.xpath(‘.//text()’)
    l=”.join(“”.join(content).split()).replace(‘”‘,””)
    lst.append(l)
    print(lst)

  • 資深大佬 : CLCLCLCLCL

    @2bin 是的, 循环一下 a 标签就行, 看你想用哪个了

  • 資深大佬 : dongxiao

    html.xpath(“string(//a)”)

  • 主 資深大佬 : 2bin

    @zyb201314
    @CLCLCLCLCL
    谢谢两位,已经解决

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具