python - 我如何在 BeautifulSoup 中使用 lxml-xml 获取页面内容
问题描述
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 页面吗?
解决方案
parserlxml-xml
等于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.
推荐阅读
- angularjs - 如何在angular js中设置日期输入的值?
- php - 无法从 PHP 访问 mysql 中 Nodejs 应用程序保存的数据
- angular - 我想保存选择它正确保存的对象并在 json 中返回对象但无法绑定返回的对象
- javascript - 画布:如何围绕指定的紫色点从指定的橙色点到指定的绿色点绘制螺旋线
- gitkraken - 当我单击标签“标记全部已解决”时,gitkraken 会做什么?
- python - 在 LSTM 中处理长时间步长序列
- python-3.x - 如何从python 3中的列表数组访问
- python - 检测csv python中的奇怪字符
- javascript - 在java脚本中转换为困难的数组对象
- java - Spring Boot - 多对多关系的分页与额外的列