用Python格式化HTML代码

2024-09-27 19:31:57 发布

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

我在CSV文件的列中有一个url列表。我想使用Python遍历所有的URL,从URL下载HTML代码的特定部分,并将其保存到下一列。在

例如: 我想从这个URL中提取这个div并将其写入下一列。在

<div class="info-holder" id="product_bullets_section">
<p>
VM−2N ist ein Hochleistungs−Verteilverstärker für Composite− oder SDI−Videosignale und unsymmetrisches Stereo−Audio. Das Eingangssignal wird entkoppelt und isoliert, anschließend wird das Signal an zwei identische Ausgänge verteilt.
<span id="decora_msg_container" class="visible-sm-block visible-md-block visible-xs-block visible-lg-block"></span>
</p>
<ul>
<li>
<span>Hohe Bandbreite — 400 MHz (–3 dB).</span>
</li>
<li>
<span>Desktop–Grösse — Kompakte Bauform, zwei Geräte können mithilfe des optionalen Rackadapters RK–1 in einem 19 Zoll Rack auf 1 HE nebeneinander montiert werden.</span>
</li>
</ul>
</div>

我有这个代码,HTML代码保存在变量HTML中:

^{pr2}$

目前HTML代码相当难看。我怎样才能从变量html中删除除了要提取的div之外的所有内容?在


Tags: csv代码dividurlhtmlliul
3条回答

在本例中,您可以使用BeautifulSoup获取具有特定id的div:

import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html)
div = soup.find(id="product_bullets_section")

假设你的所有网页都有相同的结构,你可以用这段代码解析html。它将查找id为product_bullets_section的第一个div。html中的id应该是唯一的,但是给定的网站有两个相等的id,因此我们通过切片获得第一个id,并将解析后的div转换回包含html的字符串。在

import csv
import urllib.request

from bs4 import BeautifulSoup

with open("urls.csv", "r", newline="", encoding="cp1252") as f_input:
    csv_reader = csv.reader(f_input, delimiter=";", quotechar="|")
    header = next(csv_reader)
    items = [row[0] for row in csv_reader]

items = ['https://www.kramerav.com/de/Product/VM-2N']
with open("results.csv", "w", newline="") as f_output:
    csv_writer = csv.writer(f_output, delimiter=";")
    for item in items:
        html = urllib.request.urlopen(item).read()
        the_div = str(BeautifulSoup(html).select('div#product_bullets_section')[0])

为什么不使用^{} - Simple HTML and XHTML parser?在

示例:

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

    parser = MyHTMLParser()

然后使用parser.feed(data)(其中data是str)

相关问题 更多 >

    热门问题