如何使用Beautiful Soup检索具有多个属性的对象?

huangapple go评论65阅读模式
英文:

How to retrieve an object with Beautiful Soup that has several atttributes?

问题

I am using the find function to retrieve this object:

<h1 data-testid=“organization-cover-title” class=“sc-1wcv2gl-2 kpUYKd”>Company</h1>

With this code below, it returns a NoneType

company = soup.find(‘h1’, attrs = {‘data-testid’:‘organization-cover-title’, ‘class’:‘sc-1wcv2gl-2 kpUYKd’}).string

It also does not return a string with one or the other attribute.

Would you be so kind as to find a solution?
Thanks

英文:

I am using the find function to retrieve this object:

<h1 data-testid=“organization-cover-title” class=“sc-1wcv2gl-2 kpUYKd”>Company</h1>

With this code below, it returns a NoneType

company = soup.find(‘h1’, attrs = {‘data-testid’:‘organization-cover-title’, ‘class’:‘sc-1wcv2gl-2 kpUYKd’}).string

It also does not return a string with one or the other attribute.

Would you be so kind as to find a solution?
Thanks

答案1

得分: 1

Your example is using curly quotes in HTML and CODE that are the quotation marks used in good typography.

You have to use the straight single quote (') or the straight double quote (") to get it working in both HTML and CODE.

from bs4 import BeautifulSoup
html = '''

Company

'''
soup = BeautifulSoup(html)

soup.find('h1', attrs = {'data-testid':'organization-cover-title', 'class':'sc-1wcv2gl-2 kpUYKd'}).get_text()

英文:

Your example is using curly quotes in HTML and CODE that are the quotation marks used in good typography.

You have to use the straight single quote (') or the straight double quote (") to get it working in both HTML and CODE.

from bs4 import BeautifulSoup
html = '''
<h1 data-testid="organization-cover-title" class="sc-1wcv2gl-2 kpUYKd">Company</h1>
'''
soup = BeautifulSoup(html)

soup.find('h1', attrs = {'data-testid':'organization-cover-title', 'class':'sc-1wcv2gl-2 kpUYKd'}).get_text()

答案2

得分: 0

代码部分不要翻译,只返回翻译好的部分:

The code was right actually. It works.

英文:

The code was right actually. It works

huangapple
  • 本文由 发表于 2023年5月10日 16:22:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76216315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定