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

时间:2017-06-12 12:37:11

标签: python web-scraping beautifulsoup wikipedia

我正在维基百科上没有上课的表格,并且到目前为止得到了以下输出:

<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新手,必须弄清楚它的工作原理。希望有人能在这里帮助我。

1 个答案:

答案 0 :(得分:1)

要获取引号中包含的值,您可以使用.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)
相关问题