Skip to main content
 首页 » 编程设计

python之打印某些 HTML Python Mechanize

2025年05月04日10xiaohuochai

我正在制作一个用于自动登录网站的小型 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> 

但是我如何只提取和打印名字 John Appleseed?

顺便说一句,我在 Mac 上使用 Pythons 的 Mechanize。

请您参考如下方法:

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