簡體   English   中英

使用lxml或??? 從網頁中提取信息

[英]Using lxml or ??? to extract information from webpages

目前,我有以下代碼:

# 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:<p class =“ author-name”>某些名稱</ p>
可能性2:rel =“ author”>某些名稱</a>

我要提取作者姓名。 我的邏輯如下:

檢查所有類的“作者名”-如果找到,請給我標簽內的文字。 如果找不到,請檢查“ rel =“ author”-如果找到,請給我標簽內的文字。如果沒有,請打印“ No Author Found”

我該怎么做? 我可以使用regex,lxml等。 什么是最優雅的方式?

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM