我是Python的新手,正在学习如何使用beauthoulsoup来抓取网页。首先,我只是用雅虎的HTML代码:
我想从第577行到633行的链接列表中获取它们的URL和标题,并将其放入Python中的表中。在
到目前为止,我有以下情况:
from bs4 import BeautifulSoup
myURL = "http://www.yahoo.com"
myPage = requests.get(myURL)
yahoo = BeautifulSoup(myPage.content)
print yahoo.prettify()
YahooList = yahoo.find('ul', class_="Pos(r) Miw(1000px) Pstart(9px) Lh(1.7) Reader-open_Op(0) mini-header_Op(0)")
print YahooList
我不知道该如何继续下去。我找到的所有例子都是为了从表格中抓取网页,但我在列表中找不到太多的例子。在
有人有什么建议吗?在
谢谢, 尼克
如果你只需要刮去特定的线,你需要先把这些线刮到。我建议使用^{} 和列表切片来获取它们。在
例如:
输出为:
^{pr2}$r.text.splitlines()
按行拆分HTML源代码,并给出一个列表。[575:634]
是一个列表切片,它对列表进行切片,并给出从576到634的行。我又添加了两行,因为没有它们,输出将是:这不是一个有效的HTML代码块。
^{} 通过
\n
加入列表,并给出另一个所需的字符串。在我们有了特定的线路之后:
soup.find_all('a')
查找字符串(HTML代码块)中的所有<a>
HTML标记,并给出这些标记的列表。在{{{cd8>使用
也可以使用list comprehension将结果放入列表中,而不是打印出来:
l
是您要查找的列表。在如果您还想获得这些链接的标题,可以使用} :
i.text
来获取。但是,Python中没有table object,我想您的意思是^{所以您可以使用
{i.text: i.get('href') for i in soup.find_all('a')}
来获得您想要的dict。在在本例中,}。在
i.text
(title)是该dict中的键,例如'TV'
和{并且}。在
i.get('href')
是值(链接),例如'https://www.yahoo.com/tv/'
和{您可以通过
d[key]
访问该值,就像我上面的代码一样。在相关问题 更多 >
编程相关推荐