【问题标题】:How to use partial text instead of exact in selector?如何在选择器中使用部分文本而不是精确文本?
【发布时间】:2018-04-20 03:47:55
【问题描述】:

我用 python 编写了一个脚本来从一个 torrent 站点收集电影名称及其类型。由于BeautifulSoup 不支持伪选择器,我找到了一种技术来克服它。我目前面临的唯一问题是,要获得结果,下面脚本中的反逗号内的文本必须准确。有什么方法可以在部分匹配中使用类似于:contains 属性的东西,这样即使我的查询中的文本包含部分单词,我仍然会解析我所追求的Genre。 [预计在脚本中使用Gennre:enr 而不是Genre:]

这是脚本:

import requests 
from bs4 import BeautifulSoup

soup = BeautifulSoup(requests.get("https://www.yify-torrent.org/search/1080p/").text,"lxml")
for title in soup.select("div.mv"):
    names = title.select("h3 a")[0].text
    genre = ' '.join([item.next_sibling for item in title.select(".mdif li b") if item.text=="Genre:"])
    print(names, genre)

结果:

Swelter (2014) 1080p Action
Larry Crowne (2011) 1080p Comedy
Terminal Island (1973) 1080p Action
Heart of Midnight (1988) 1080p Drama
The Lift (1983) 1080p Fantasy

【问题讨论】:

  • 我不明白你的问题;但是,我会注意到 Scrapy 支持伪元素等:请参阅doc.scrapy.org/en/latest/topics/selectors.html
  • 有时我上面使用的文本足够长,可以像这样使用,这就是为什么我想进行部分匹配而不是使用确切的文本。我也使用过scrapy和lxml。但是我也想知道它如何在 BeautifulSoup 中使用。谢谢。

标签: python python-3.x web-scraping beautifulsoup css-selectors


【解决方案1】:

您可以简单地使用in 运算符来检查字符串是否包含子字符串:

genre = ' '.join([item.next_sibling for item in title.select(".mdif li b") if "Genre:" in item.text])

您可以使用if "Genre:" in item.text 以及if "nre:" in item.textif "Gen" in item.text 等...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    相关资源
    最近更新 更多