xpath下怎么提取包含某个字符串的属性值

1.最近在爬取某个网站时,遇到了一个问题,怎么提取包含了某个字符串的属性值?
2.大致内容是这样的:
<a href="thread-115861-1-1.html"
<a href = "javavoid(0)"
我现在只想提取包含"thread"字符串的href属性值,即"thread-115861-1-1.html",请问我应该怎么写?我试过contains,但是contains好像只能对text()进行筛选,对属性值不能进行筛选。
3.希望各位朋友能够不吝赐教,谢谢

阅读 5.7k
2 个回答

已经找到了答案,之前是自己没有了解语法,可以用xpath下的语法,用starts-with或者contains都可以。
具体语法如下:
//a[starts-with(@href,"thread")]/@href
//a[contains(@href,"thread")]/@href

不知道题主用BeautifulSoup可不可以?类似这种。

In [1]: from bs4 import BeautifulSoup

In [2]: soup = BeautifulSoup("""
   ...: <a href="thread-115861-1-1.html"></a>
   ...: <a href = "javavoid(0)"></a>
   ...: """)

In [3]: res_list = []
   ...: for item in soup.find_all("a"):
   ...:     if "thread" in item["href"]:
   ...:         res_list.append(item["href"])
   ...:

In [4]: res_list
Out[4]: ['thread-115861-1-1.html']
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题