【问题标题】:Using lxml or ??? to extract information from webpages使用 lxml 或 ???从网页中提取信息
【发布时间】:2014-11-30 17:52:30
【问题描述】:

目前我有以下代码:

# Import der Pythonmodule
import urllib
import lxml
import mechanize
import sys

# Verbindung zum URL aufbauen
try:
    URL = urllib.urlopen("http://...")

except:
    print "Verbindung zum URL fehlgeschlagen"
    sys.exit(0)

# Quellcode des URL lesen 
URL_quellcode = URL.readlines()

# Verbindung zum URL beenden
URL.close()

到目前为止一切顺利,我可以打开并阅读 URL 的来源。现在我想看看各种可能性来提取一些东西。

可能性 1:

某个名字


可能性2: rel="author">某个名字

我想提取作者姓名。我的逻辑如下:

检查“作者姓名”的所有类 - 如果找到,请给我标签内的文本。如果找不到,请检查“rel="author" - 如果找到,请给我标签内的文字。如果没有,请打印“未找到作者”

我该怎么做?我可以使用正则表达式、lxml 或其他任何东西。什么是最优雅的方式?

【问题讨论】:

    标签: python regex web-scraping lxml urllib


    【解决方案1】:

    使用BeautifulSoup

    from bs4 import BeautifulSoup
    
    document_a = """
    <html>
        <body>
            <p class="author-name">Some Name</p>
        </body>
    </html>
    """
    
    document_b = """
    <html>
        <body>
            <p rel="author-name">Some Name</p>
        </body>
    </html>
    """
    def get_author(document):
        soup = BeautifulSoup(document_a)
        p = soup.find(class_="author-name")
        if not p:
            p = soup.find(rel="author-name")
            if not p:
                return "No Author Found"
        return p.text
    
    print "author in first document:", get_author(document_a)
    print "author in second document:", get_author(document_b)
    

    结果:

    author in first document: Some Name
    author in second document: Some Name
    

    【讨论】:

    • 太棒了,就像一个魅力。我现在从 BS 开始,真的很有趣!无论如何,我想知道这将如何处理未知数量的 URL。我将从 .txt 文件中加载它们,因此我不能像 document_a .b .c 等那样做。基本上输出将是 URL,Authorname 作为带有一个打印操作的列表。
    • 在这种情况下,您可以执行print [url, get_author(get_document(url)) for url in my_file] 之类的操作。您必须编写一个 get_document 函数来从给定的 url 检索 HTML 数据。
    猜你喜欢
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多