将 BeautifulSoup 指向某个 <tr> class
Pointing BeautifulSoup towards a certain <tr> class
我正在尝试让 BeautifulSoup 获取 "Units Sold" 列中的数字:
from bs4 import BeautifulSoup
from urllib import urlopen
html = urlopen('http://www.the-numbers.com/home-market/dvd-sales/2007')
soup = BeautifulSoup(html.read(), 'lxml')
units = soup.find_all("td", {"class": "data"})
print(units)
这会输出所有列中的所有信息 - 所以我接近了!如何将其缩小到 "Units Sold" 列以获取结果?
如何遍历 table 上的行并获取第三个单元格文本:
for row in soup.select("div#page_filling_chart table tr")[1:]:
cells = row('td')
print cells[1].get_text(strip=True), cells[2].get_text(strip=True)
此处 div#page_filling_chart table tr
是一个 CSS selector,它将匹配 table
内的 tr
个元素 div
内的 id="page_filling_chart"
元素。
打印 "Title" 和 "Units Sold" 列的内容:
Pirates of the Caribbean - At World's End 13,699,490
Transformers 13,251,378
...
Halloween (2007) 1,172,994
Music and Lyrics 1,158,903
我正在尝试让 BeautifulSoup 获取 "Units Sold" 列中的数字:
from bs4 import BeautifulSoup
from urllib import urlopen
html = urlopen('http://www.the-numbers.com/home-market/dvd-sales/2007')
soup = BeautifulSoup(html.read(), 'lxml')
units = soup.find_all("td", {"class": "data"})
print(units)
这会输出所有列中的所有信息 - 所以我接近了!如何将其缩小到 "Units Sold" 列以获取结果?
如何遍历 table 上的行并获取第三个单元格文本:
for row in soup.select("div#page_filling_chart table tr")[1:]:
cells = row('td')
print cells[1].get_text(strip=True), cells[2].get_text(strip=True)
此处 div#page_filling_chart table tr
是一个 CSS selector,它将匹配 table
内的 tr
个元素 div
内的 id="page_filling_chart"
元素。
打印 "Title" 和 "Units Sold" 列的内容:
Pirates of the Caribbean - At World's End 13,699,490
Transformers 13,251,378
...
Halloween (2007) 1,172,994
Music and Lyrics 1,158,903