我试图从一个新闻网站页面(从它的档案之一)得到链接。我用Python编写了以下几行代码:
main.py
包含:
import mechanize
from bs4 import BeautifulSoup
url = "http://www.thehindu.com/archive/web/2010/06/19/"
br = mechanize.Browser()
htmltext = br.open(url).read()
articletext = ""
soup = BeautifulSoup(htmltext)
for tag in soup.findAll('li', attrs={"data-section":"Business"}):
articletext += tag.contents[0]
print articletext
中对象的示例标签内容[0]:
<a href="http://www.thehindu.com/business/itc-to-issue-11-bonus/article472545.ece" target="_blank">ITC to issue 1:1 bonus</a>
但是在运行它时,我得到了以下错误:
^{pr2}$有人能帮我解决吗??我是Python编程新手。谢谢和问候。在
我相信您可能需要尝试访问列表项中的文本,如下所示:
编辑:关于从页面获取链接的一般评论
可能最容易用来收集一堆链接并在以后检索它们的数据类型是字典。在
要使用BeautifulGroup从页面获取链接,可以执行以下操作:
^{pr2}$这将为您提供一个名为
link_dictionary
的字典,其中字典中的每个键都是一个字符串,它只是<a> </a>
标记之间的文本内容,每个值都是href
属性的值。在如何将这与您之前的尝试相结合
现在,如果我们将此问题与您之前遇到的问题结合起来,我们可以尝试以下方法:
如果这没有意义,或者你有更多的问题,你需要先做实验,在提出另一个更清晰的新问题之前,先尝试想出一个解决方案。
你用的是林克字典。如果不是为了阅读而使用它,请尝试以下代码:
注意:
re
表示正则表达式。为此,您导入re
的模块。在您可能希望将强大的XPath查询语言与更快的^{} 模块一起使用。就这么简单:
更新@data section='Chennai'
^{pr2}$相关问题 更多 >
编程相关推荐