【问题标题】:Print function in python not working with web scrapingpython中的打印功能不适用于网络抓取
【发布时间】:2022-01-13 17:49:47
【问题描述】:

我通过抓取某个网站来获取一个字符串,然后我试图检查该字符串的第一个值(在本例中为“<h2>maanantai 10.1.</h2>”)是否包含字母“a”。如果是(就像它一样) - 打印“是”。

由于某些我不明白的原因,它不起作用。

import urllib.request
from bs4 import BeautifulSoup

url = 'https://kouluruoka.fi/menu/kouvola_koulujenruokalista'

request = urllib.request.Request(url)
content = urllib.request.urlopen(request)

parse = BeautifulSoup(content, 'html.parser')

h2_elements = parse.find_all('h2')

first_value_in_string = h2_elements[1]

# this one prints " <h2>maanantai 10.1.</h2> " as it should
print(first_value_in_string)

# this one should check if the value (first_value_in_string) contains the letter 'a' and if it does then print 'YES' but for some reason it doesnt
if 'a' in first_value_in_string:
    print('YES')

【问题讨论】:

标签: python


【解决方案1】:

first_value_in_string 数据类型为&lt;class 'bs4.element.Tag'&gt; 因此,当您比较或更好地获取文本属性时,将其转换为字符串:

if 'a' in first_value_in_string.text:
    print('YES')

或者当你分配它时:

first_value_in_string = h2_elements[1].text

或者你可以使用 .string 属性

【讨论】:

  • 你也可以first_value_in_string.string.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多