如何获取 BeautifulSoup 对象的某些部分

How to get certain parts of a BeautifulSoup Object

我在没有 class 的维基百科上抓取 table,目前得到以下输出:

<a href="/wiki/link1" title="name1">name1</a>
<a href="/wiki/link2" title="name2">name2</a>
<a href="/wiki/link3" title="name3">name3</a>

我需要的是引号中的内容和尖括号之间的名称,但我找不到如何为拿到它,为实现它。到目前为止,这是我的代码。

import requests
from bs4 import BeautifulSoup

url = 'https://en.wikipedia.org/wiki/List_of_United_States_cities_by_population'
source_code = requests.get(url)                     # Read source code
plain_text = source_code.text                       # Source code in unicode
soup = BeautifulSoup(plain_text, "html.parser")     # create BS object

table = soup.find(text="2016 rank").find_parent("table")
for row in table.find_all("tr")[1:]:
    print(row.find_all('a')[0])

我是 BS 的新手,必须弄清楚它是如何工作的。希望有人能在这里帮助我。

要获取引号中包含的值,您可以使用 .attrs 字段 - 它是一个字典标签属性及其值:

print(row.find_all('a')[0].attrs['href'])
print(row.find_all('a')[0].attrs['title'])

提取>字符后的部分,可以使用.contents:

print(row.find_all('a')[0].contents)