python爬虫采用asyncio模块的异步操作,当请求多个url时,返回的页面源代码是几个url源代码合并在一起的,该怎么办呢?
import re
import os
import json
import pprint
import asyncio
import aiohttp
import requests
from lxml import etree
from flashtext import KeywordProcessor
from moviepy.editor import concatenate_videoclips, VideoFileClip, AudioFileClip
class Bspider():
def __init__(self,url,outpath):
self.url =url
self.outpath = outpath
async def spider_full(self):
self.re5 = re.compile(r'window.__playinfo__=(.*)')
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0',
'Referer': 'https://www.bilibili.com/'
}
# html_list = []
async with aiohttp.ClientSession() as reqt_session:
async with reqt_session.get(self.url, headers=self.headers) as resq:
resq_text = await resq.text(encoding='utf-8')
print(resq_text)
如上述代码,是b站爬虫,采用异步协程的操作,当进行多个url异步的时候,发现print出来的resq_text的结果是多个url的页面源代码组合在一起的(即多个html标签),我希望能够提出每一个url单独的页面源代码,请问该怎么办呀?
有几个简单的办法:
import urllib.request
response=urllib.request.urlopen("https://www.baidu.com")
html=response.read()
print(html)
这段代码会爬取百度的前端源代码,读者可以登录到百度网站上点鼠标右键选择查看源代码,来对比打印结果。如下图所示。结果似乎有点出人意料,为什么是一行输出。我们看到图中我用红线标记的b,这是python中bytes数据类型的显示方式。
如果我们要获取字符串类型的输出,还需要对代码进行一下加工,也就是将bytes进行转码,在python中bytes转string类型需要用到decode方法,想法用string转bytes需要用到encode方法。
import urllib.request
response=urllib.request.urlopen("https://www.baidu.com")
html=response.read().decode()
print(html)