我正在学习BS4,我正在尝试从流行的站点中抓取几个表、列表等,以使自己熟悉th语法。我有一个困难的时间得到一个正确的格式列表。这是代码:
from bs4 import BeautifulSoup
import urllib2
import requests
headers = {
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Pragma': 'no-cache',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36',
'Accept-Language': 'en-US,en;q=0.8'
}
url = 'https://www.yahoo.com'
req = urllib2.Request(url, None, headers)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
terms = soup.find('ol').get_text()
print terms它打印以下列表:
1Amanda Knox2Meagan Good3Dog the Bounty Hunter4Adrienne Bailon5Powerball winner6Gillian Anderson7Catherine Zeta-Jones8Mickey Rourke9Halle Berry10Lake Tahoe hotels正确的术语由数字分隔,这将增加一个额外的工作级别,以解析该文件,使其读到kike "Amanda Knox“、"Megan Good”等等。
因为我对BS4不是很熟悉,所以在我对术语的定义中有什么方法可以在"tile=“标签之后得到这些术语吗?
发布于 2014-08-14 03:25:02
这是因为ol标记中有多个元素,get_text()加入了每个标记的文本。
相反,您可以使用CSS Selector来获取实际的术语:
for li in soup.select('ol.trendingnow_trend-list > li > a'):
print li.get_text()指纹:
Hope Solo
Christy Mack
Dog the Bounty Hunter
Adrienne Bailon
Powerball winner
Catherine Zeta-Jones
Mickey Rourke
Valerie Velardi
Halle Berry
Lake Tahoe hotelsol.trendingnow_trend-list > li > a css选择器将直接位于li内部的每个a标记与trendingnow_trend-list类属性匹配,后者就在ol标记内。
FYI,这是从右上角的块中获取Trending Now术语的列表。
https://stackoverflow.com/questions/25299497
复制相似问题