打印某些HTML Python Mechaniz

2024-09-28 17:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个小的python脚本,用于自动登录网站。但我被卡住了。

我想在终端上打印一小部分html,位于网站html文件的这个标记中:

<td class=h3 align='right'>&nbsp;&nbsp;John Appleseed</td><td>&nbsp;<a href="members_myaccount.php"><img border=0 src="../tbs_v7_0/images/myaccount.gif" alt="My Account"></a></td>

但是我该如何提取并打印出名字,约翰·阿普雷塞德?

顺便说一句,我在mac电脑上用Python的机械装置。


Tags: 文件标记right脚本终端网站htmljohn
3条回答

可以使用解析器提取文档中的任何信息。我建议您使用lxml模块。

这里有一个例子:

from lxml import etree
from StringIO import StringIO

parser = etree.HTMLParser()

tree = etree.parse(StringIO("""<td class=h3 align='right'>&nbsp;&nbsp;John Appleseed</td><td>&nbsp;<a href="members_myaccount.php"><img border=0 src="../tbs_v7_0/images/myaccount.gif" alt="My Account"></a></td>"""),parser)


>>> tree.xpath("string()").strip()
u'John Appleseed'

有关lxmlhere的详细信息

Mechanize只适合获取html。一旦您想从html中提取信息,您可以使用例如BeautifulSoup。(另见我对类似问题的回答:Web mining or scraping or crawling? What tool/library should I use?

根据<td>在html中的位置(您的问题不清楚),可以使用以下代码:

html = ... # this is the html you've fetched

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(html)
# use this (gets all <td> elements)
cols = soup.findAll('td')
# or this (gets only <td> elements with class='h3')
cols = soup.findAll('td', attrs={"class" : 'h3'})
print cols[0].renderContents() # print content of first <td> element

由于您还没有提供页面的完整HTML,现在唯一的选择是使用string.find()或正则表达式。

但是,找到它的标准方法是使用xpath。看这个问题:How to use Xpath in Python?

您可以使用firefox的“inspect element”特性获取元素的xpath。

例如,如果您想在stackoverflow站点中找到用户名的XPATH。

  • 打开firefox并登录到网站,右键单击用户名(在我的例子中是shadyabhi),然后选择Inspect Element。
  • 将鼠标放在标记上或右键单击它并“复制xpath”。

enter image description here

相关问题 更多 >