python - 如何显示网站上的句子?

标签 python screen-scraping

我决定做这个小项目来学习如何使用 mechanize。现在它会转到urbandictionary,在搜索表单中填写单词“skid”,然后按提交并打印出HTML。

我想要它做的是找到第一个定义并将其打印出来。我到底该怎么做呢?

这是我到目前为止的源代码:

import mechanize

br = mechanize.Browser()
page = br.open("http://www.urbandictionary.com/")

br.select_form(nr=0)
br["term"] = "skid"
br.submit()

print br.response().read()

这是存储定义的位置:

<div class="definition">Canadian definition: Commonly used to refer to someone   who      stopped evolving, and bathing, during the 80&#x27;s hair band era.  Generally can be found wearing AC/DC muscle shirts, leather jackets, and sporting a <a href="/define.php?term=mullet">mullet</a>.  The term &quot;skid&quot; is in part derived from &quot;skid row&quot;, which is both a band enjoyed by those the term refers to, as well as their address.  See also <a href="/define.php?term=white%20trash">white trash</a> and <a href="/define.php?term=trailer%20park%20trash">trailer park trash</a></div><div class="example">The skid next door got drunk and beat up his old lady.</div>

您可以看到它存储在 div 定义中。我知道如何在源代码中搜索 div,但我不知道如何获取标签之间的所有内容然后显示它。

最佳答案

我认为正则表达式足以完成此任务(根据您的描述)。试试这个代码:

import mechanize, re

br = mechanize.Browser()
page = br.open("http://www.urbandictionary.com/")

br.select_form(nr=0)
br["term"] = "skid"
br.submit()

source =  br.response().read()

regex = "<div class=\"definition\">(.+?)</div>"
pattern = re.compile(regex)
r=re.findall(pattern,source)
print r[0]

这将显示标签之间的内容(没有示例部分,但它们完全相同),但我不知道您想如何处理此内容中的标签。如果你想要他们在那里,那就这样吧。或者,如果您想删除它们,可以使用类似 re.replace() 的方法。

关于python - 如何显示网站上的句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18406243/

相关文章:

python - 如何在 Mechanize/Python 中设置隐藏形式的值?

python - vim中如何计算当前文件位置? (扩展值 ('%:p' ))

java - 避免与 JSoup 进行无空格连接

python - urllib2 通过错误获取响应

python - TensorFlow:保存前使用 python 量化模型

python - 使用 beautiful soup python 循环抓取 URL

c# - 可以在开关 {case} 中使用通配符或字符串 "contains"吗?注意 : wordy

python - 如何 scrapy 处理 dns 查找失败

python - 如何在 PyQt5 中的外部事件过滤器方法中获取变量值?

python - 定义在 Python 中给出给定范围内的随机值的函数