【问题标题】:Python to parse web page for 'title' [closed]Python解析“标题”的网页[关闭]
【发布时间】:2012-12-17 17:58:28
【问题描述】:

我希望能够解析网页并返回标题正好包含 4 个字母的任何元素。

例如:

<li><a href="test.com/dogs" title="dogs"></a></li>
<li><a href="test.com/cat" title="cat"></a></li>
<li><a href="test.com/horse" title="horse"></a></li>
<li><a href="test.com/eels" title="eels"></a></li>

在本例中,我想返回一个包含“dogs”和“eels”的数组,因为标题正好包含 4 个字符。我该怎么做呢?谢谢!

【问题讨论】:

  • 存在 XML 解析器。由于您询问的是 Python,请在 Google 上搜索“beautifulsoup”。
  • 每天必须多久解释一次应该使用 HTML 或 XML 解析器而不是其他任何东西来解析标记?万亿次? -1 来自我
  • @user1833746 在 OP 的辩护中,他确实问过“我该怎么做”,答案就像 Jack Maney 建议的那样。
  • 您无法使用正则表达式可靠地解析 HTML。 htmlparsing.com/python.html 有如何使用解析器的示例。

标签: python regex parsing module


【解决方案1】:

你应该使用BeautifulSoup

使用它,您可以执行以下操作:

import urllib2
from BeautifulSoup import BeautifulSoup

url = # put url here
page = urllib2.urlopen(url)
text = page.read()
page.close()
soup = BeautifulSoup(text)

L = []
for x in soup.findAll('li'):
    link = x.a
    if link.has_key('title'):
        if len(link['title']) == 4:
            L.append(link['title'])
print L

【讨论】:

  • 老兄.. 这会很好。 Beautifulsoup 只是一个 .py 文件,您可以像这样导入:from BeautifulSoup import BeautifulSoup
  • 由于某种原因,它没有返回任何东西。我已经尝试在 'li' 和 'a' 上执行 'soup.findAll',即使我尝试在 for 循环中打印 x 也不会返回任何内容
  • 我的错,我修好了。现在可以用了吗?
  • 仍然没有运气:/ 回来 []
  • 你确定吗?我通过将您的 html 代码直接粘贴到 soup 字符串中来测试它,输出为:[u'dogs', u'eels']
【解决方案2】:

我知道解析 html 被认为是不好的美德,但我确实喜欢直截了当的方法。

 #!/usr/bin/env python
 import re
 res_array = []
 for line in open('inputdata','r'):
     res = re.findall('title=\"[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]\"',line)
     if res :
         res_array.append(res[0].split('"')[1]) 
 print res_array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 2021-01-31
    • 2014-03-22
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2013-01-25
    相关资源
    最近更新 更多