从<a href="data:text/csv;...content">中提取内容

时间:2019-10-29 22:16:04

标签: python web-scraping python-requests lxml data-uri

具有CSV内容的html标签<a>的字符串值:

href = "data:text/csv;charset=UTF-8,%22csvcontentfollows"

是否可以通过标准模块(请求,lxml,纯python)的方法在没有此类元标头data:text/csv;charset=UTF-8的情况下获取这样的CSV内容?

我不希望使用手动文本解析(通过regexp,index / startswith,split / partition)。

更新:

谢谢,我知道如何使用html。我对这种元标头的问题。我重新制定了。

1 个答案:

答案 0 :(得分:1)

这是三种可能的解决方案。第一个使用本机Python的urllib.request.urlopen函数。第二个使用第三方库lxml。第二个使用本地html.parser模块中的HTMLParser类。第二和第三者使用第三方库来解析data URLs

python-datauri
html_string = """
<a href="data:text/csv;charset=UTF-8,%22csvcontentfollows">
<a href="data:text/csv;charset=UTF-8,%22csvcontentfollows">
<a href="data:text/csv;charset=UTF-8,%22csvcontentfollows">
"""

from contextlib import ExitStack
from urllib.request import urlopen
import lxml.etree

HREF = "href"

tree = lxml.etree.fromstring(html_string, lxml.etree.HTMLParser())

uris = (
    item.attrib[HREF]
    for item in tree.iterdescendants()
    if HREF in item.attrib
)

with ExitStack() as stack:
    resources = (stack.enter_context(urlopen(uri)) for uri in uris)
    data = [fh.read().decode() for fh in resources]
print(data)

输出: ['csvcontentfollows', 'csvcontentfollows', 'csvcontentfollows']

import lxml.etree
from datauri import DataURI

tree = lxml.etree.fromstring(html_string, lxml.etree.HTMLParser())

HREF = "href"

uris = (
    DataURI(item.attrib[HREF])
    for item in tree.iterdescendants()
    if HREF in item.attrib
)
attrs = ("mimetype", "charset", "is_base64", "data")
print([{attr: getattr(uri, attr) for attr in attrs} 
       for uri in uris])

输出:

[{'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}, {'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}, {'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}]


from html.parser import HTMLParser
from datauri import DataURI

uri_attrs = ("mimetype", "charset", "is_base64", "data")

class MyHTMLParser(HTMLParser):

    def __init__(self):
        super().__init__()
        self.data = []

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            for attr, value in attrs:
                if attr == "href":
                    for key, value in attrs:
                        uri = DataURI(value)
                        self.data.append({attr: getattr(uri, attr) for attr in uri_attrs})

parser = MyHTMLParser()
parser.feed(html_string)
print(parser.data)

输出:

[{'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}, {'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}, {'mimetype': 'text/csv', 'charset': 'UTF-8', 'is_base64': False, 'data': 'csvcontentfollows'}]