我决定学习用于数据分析的python 2.7编码,并一直在youtube上观看许多教程,以对基本知识有很好的理解。
我正处于一个阶段,我想创建简单的网络爬虫用于教育目的,只是为了学习不同的技术,并且习惯一些编码。
我正在关注网络爬虫的教程,但是我不确定几件事。这是我到目前为止的内容:
import requests
from bs4 import BeautifulSoup
url = 'http://www.aflcio.org/Legislation-and-Politics/Legislative-Alerts'
r = requests.get(url)
plain_text = r.text
soup = BeautifulSoup(plain_text, 'html.parser')
statements = soup.findAll('div','ec_statements')
for link in statements:
print (link.contents)
我似乎无法分开href链接并显示文本和日期信息。
我希望它看起来像这样:
有人可以提供一些有关为何采取这些步骤的信息吗?
非常感激!
一些代码可以帮助您。在bs4中,所有节点都是连接,您都读取了一个“ link”节点(实际上是一个div),您想让他的孩子喜欢标记a,所以link.a
还可以。
那么,一个节点具有两个部分值,一个是attribute,由by进行访问a['href']
,而content则由进行访问a.text
。
for link in statements:
print(link.a['href'])
ps:这是链接变量:
<div id="legalert_title"><a href="/Legislation-and-Politics/Legislative-Alerts/Letter-to-Representatives-opposing-the-Fairness-in-Class-Action-Litigation-and-Furthering-Asbestos-Claim-Transparency-Act">Letter to Representatives opposing the "Fairness in Class Action Litigation and Furthering Asbestos Claim Transparency Act"</a></div>
这是link.a:
<a href="/Legislation-and-Politics/Legislative-Alerts/Letter-to-Representatives-opposing-the-Fairness-in-Class-Action-Litigation-and-Furthering-Asbestos-Claim-Transparency-Act">Letter to Representatives opposing the "Fairness in Class Action Litigation and Furthering Asbestos Claim Transparency Act"</a>
这是link.a ['href']:
/Legislation-and-Politics/Legislative-Alerts/Letter-to-Representatives-opposing-the-Fairness-in-Class-Action-Litigation-and-Furthering-Asbestos-Claim-Transparency-Act
这是.text:
Letter to Representatives opposing the "Fairness in Class Action Litigation and Furthering Asbestos Claim Transparency Act"
所有的html都是这样,也许您需要学习一点html。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句