0x00 写在前面
最近开始学习Python的爬虫,就试着写了写笔趣阁小说的爬虫,由于是初学,所以正则,bs4,xpath都用了用,下面是正文
0x01 搜索页面
首先是对搜索页面的分析,网址如下:
http://www.xbiquge.la/modules/article/waps.php
先对查找方式进行测试
f12查看header
是post方法,进一步查看数据
发现数据名是searchkey,内容并没有进行加密
开始写代码
murl = 'http://www.xbiquge.la/modules/article/waps.php'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0"}
data={
'searchkey':book}
response=requests.post(url=murl,data=data,headers=headers)
response.encoding = "utf-8"
code=response.text
这部分代码是写在函数getBook()里的,其中book是向函数传入的值,response.encoding="utf-8"这里是为了让code中的中文可以正常显示
然后我们接着分析网页
我们发现这里的搜索结果都写在这个table里,且书名的标签是td,class为even,作者也在 td class=“even” 中,这就好办了,我们可以先找到class=even的所有标签,接下来我们可以用bs4和正则表达式进行元素定位
code=response.text
soup=BeautifulSoup(code,'lxml')
tab=soup.select('.even')
all=re.findall(r'<td class="even">(.*?)</td>',str(tab))
if len(all)==0:
return None
这里是接着上边的函数写的,tab是用bs4定位到的所有class=even的标签源码,再接着用正则获得我们想要的内容,当然,这里得到的all的数据并不符合我们想要的数据形式,先回到网站
我们可以发现,由于这里的区别,我们就能区分开书名,作者和网址,首先我们用正则把url和书名拿到,而all中的所有数据都是even的,作者单独占了一个带有even的标签,我们输出all后不难发现,第1,3,5…即
i%2!=0
的数据都是作者的,所以我们有
name=re.findall(r'target="_blank">(.*?)</a>',str(all))
author=[]
url=re.findall(r'href="(.*?)"',str(all))
for i,n in enumerate(all):
if i%2!=0:
author.append(n)
for i in range(len(name)):
if i == 0:
print('序号\t书名\t作者\t网址')
print('['