【问题标题】:How i get content of page using lxml-xml in BeautifulSoup我如何在 BeautifulSoup 中使用 lxml-xml 获取页面内容
【发布时间】:2020-08-31 07:03:50
【问题描述】:
import asyncio
import aiohttp
import lxml
from bs4 import BeautifulSoup


async def get_content(session,url):
    async with session.get(url) as responce:
            data = await responce.read()
    return BeautifulSoup(data.decode('utf-8'), 'lxml-xml')
    

async def parse(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [asyncio.create_task(get_content(session,i)) for i in urls]
        soups = await asyncio.gather(*tasks,return_exceptions=True)
    return soups


url = "https://kolesa.kz/cars/almaty/?page={}"
urls = [url.format(i) for i in range(2,201)]

loop = asyncio.get_event_loop()
soups = loop.run_until_complete(parse(urls))
loop.close()

print(soups[0])

使用 BeautifulSoup lxml-xml 无法解析站点的 200 页内容。 汤[0] 显示此<?xml version="1.0" encoding="utf-8"?>。 我可以使用 lxml-xml 获取 html 页面吗?

【问题讨论】:

    标签: python parsing beautifulsoup utf-8 lxml


    【解决方案1】:

    解析器是lxml-xmlis equal to xml parser。您可能不想将文档解析为 XML,而是 HTML。将其更改为lxml(或html5lib/html.parser):

    async def get_content(session,url):
        async with session.get(url) as responce:
                data = await responce.read()
        return BeautifulSoup(data.decode('utf-8'), 'lxml')  # <--- change to only `lxml`
    

    那么输出是:

    <!DOCTYPE html>
    <html lang="en" xmlns:xlink="http://www.w3.org/1999/xlink">
    <head>
    <meta charset="utf-8"/>
    
    ...and so on.
    

    【讨论】:

    • 但是使用 lxml 我失去了解析速度。 lxml-xml 5秒解析200页 lxml 50秒解析
    • @AggressiveGhosts 那是因为xml 解析器没有解析整个树……它会看到文档不是有效的 XML 并放弃。 lxml 将解析整个文档,当然,这需要更多时间。我建议然后看看multiprocessing 模块。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 2013-12-07
    • 2013-07-28
    • 2019-02-24
    • 2011-03-16
    • 1970-01-01
    相关资源
    最近更新 更多