【问题标题】:Find String (Keyword) in title and description using Beautifulsoup?使用 Beautifulsoup 在标题和描述中查找字符串(关键字)?
【发布时间】:2015-11-11 14:30:46
【问题描述】:

首先:我在循环中打开一些 url 并获取 html 代码的标题和描述。 (作品)

第二:我想检查标题或描述中是否有给定的字符串(关键字)。 (不工作)


# 2 - Beautifulsoup: Soll Keywords suchen und Schema.org
kw = "optiker"
seite = obj_det.get('result',{}).get('website')
try:
    req = urllib.request.urlopen(seite).read()
    soup = BeautifulSoup(req, "html.parser")
    desc = soup.findAll(attrs={"name":"description"})
    title = soup.title.string
except:
    title = "Zugriff verweigert"
    desc = "Zugriff verweigert"
kwindesc = kw in desc
kwintitle = kw in title
print(title)
print(desc)
print(kwindesc)
print(kwintitle)
print("-----")

我的屏幕上总是显示 False。但肯定有标题带有字符串“optiker”。

【问题讨论】:

  • desctitle的类型是什么?它是某种节点对象吗?
  • 我不知道。我在学习python方面很新。我试过了kwindesc = kw in str(desc)。也不行。
  • 你能给我们一个你试图抓取的页面的例子吗?
  • 您可以使用type() 函数检查对象的类型。 print( type(desc) ) 报告什么?
  • www[.]optiker-bode[.]de - 看到标题有字符串“optiker”。所以我应该有一个真实的。

标签: python-3.x beautifulsoup


【解决方案1】:

desc 变量是标签数组,而不是字符串(对于 findAll)。您想要的信息在meta 标记的content 属性中。我稍微修改了你的代码,下面的工作正常。请注意将content 拉出的额外步骤以及使用find 而不是findAll。还进行了编辑以添加不区分大小写的比较。

url = "http://www.optiker-bode.de/brillenauswahl/marken"
page=urllib.request.urlopen(url)

soup = BeautifulSoup(page.read())

kw = "optiker"
#seite = obj_det.get('result',{}).get('website')
try:
    #req = urllib.request.urlopen(seite).read()
    #soup = BeautifulSoup(req, "html.parser")
    desc = soup.find("meta",attrs={"name":"description"}).get("content")
    title = soup.title.string
except:
    title = "Zugriff verweigert"
    desc = "Zugriff verweigert"
kwindesc = kw in desc.lower()
kwintitle = kw in title.lower()
print(title)
print(desc)
print(kwindesc)
print(kwintitle)
print("-----")

输出是

Optiker Bode | Marken
Ob Armani, JAGUAR, LIEBESKIND, Michael Kors, Oakley, Porsche, Ray-Ban oder Zeiss: Lassen Sie sich von unserer großen Markenauswahl inspirieren!
False
True
-----

【讨论】:

    猜你喜欢
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多