嘀嘀嘀嘀,这里是人间小苦瓜的削笔机(小笔记)
简简单单做个笔记吧
目前网页数据有两种,一种是静态页面:直接右键检查页面元素,然后保存成html利用Beautifulsoup来解析;另外一种是动态获取的,那就通过截取数据包,查看获取信息的网页地址,一般都是.json格式的内容,所以可以用json来解析。
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('weibo_rank.html'),'lxml')
查找的话,我一般遵守查到第一,其他的统统排第二原则。
因此我会使用beautifulsoup.find()和beautifulsoup.find_all()这两个函数来查找tag。然后使用直接粗暴的str.replace(),str.strip(),str.split()来直接截取所需要的信息。如果遇到复杂一点的,就引入re库,使用正则表达式来匹配。
- beautifulsoup部分
beautiful.find_all()可以返回所有的内容。用for进行遍历查询。
#可以用[0]来指定查询某一个值
a = soup.find_all(name='td')[0]
#用for循环进行遍历
for infor in soup.find_all(name='td'):
print(infor)
查询参数(先举例子,等有空了再统一整理吧懒懒):
例子一(需要查询的内容如下,返回的结果也是如下):
<td class="td-01 ranktop">50</td>
<td class="td-02">
<a href="/weibo?q=%23%E7%A5%9E%E5%A5%87%E5%8A%A8%E7%89%A9%E6%89%BE%E5%88%B0%E4%BA%86%23&Refer=top" target="_blank">神奇动物找到了</a>
<span>202685</span>
</td>
<td class="td-03"><i class="icon-txt icon-txt-new">新</i></td>
python代码:
td_01_1 = soup.find_all(name='td')[td_01]
td_02_1 = soup.find_all(name='td')[td_02]
td_03_1 = soup.find_all(name='td')[td_03]
例子二(需要查询的内容如下,返回的结果也是如下):
<td class="td-01 ranktop">1</td>
python代码:
soup.find_all(name='td',class_='td-01 ranktop')[0]
例子三
如果是两个class嵌套的话,目前来说我只能想到的解决办法就是用新的beautifulsoup来装旧的beautifulsoup的结果。
python代码:
card_user_list=str(soup.find_all(class_='card-user-list-a'))
soup1=BeautifulSoup(card_user_list,'lxml')
- 微博的格式
对不起微博但是我还是得说一句,它莫名其妙的格式真的给我给我整懵了。要不是为了多收集一步数据,真的从来没有认真看过。
热搜点进去之后目前发现的有三种种类的微博内页:
1.有主持人有讨论量
2.无主持人无讨论量
3.无主持人有讨论量
- 读写excel
库名:
xlwt :写入
xlrd:读取
xlwt的API手册
https://xlwt.readthedocs.io/en/latest/api.html
别人写好的函数(可以看着改改用嘿嘿):
https://blog.csdn.net/u013250071/article/details/81911434
- Scrapy库引用
https://blog.csdn.net/hoddy355/article/details/81156328
进入写好的爬虫工程,在spider文件夹下面直接新建一个.py文件,调用scrapy自带的函数就可以用代码来启动爬虫。
类似于下图这种:
如果只是一次性调用则可以使用以下的代码:
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
'''一次性调用可,多次调用不可'''
process = CrawlerProcess()
process.crawl('demo') #'demo'为当前爬虫名
process.start()
若使用永真的循环,希望按照某一特点时间段多次来爬取信息的时候上述的代码就会报错:
“twisted.internet.error.ReactorNotRestartable”
是scrapy在定义的时候是不允许多次start的,因此需要对代码部分进行改良:
import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from twisted.internet import reactor
from twisted.internet.task import deferLater
def sleep(self, *args, seconds):
"""Non blocking sleep callback"""
return deferLater(reactor, seconds, lambda: None)
process = CrawlerProcess(get_project_settings())
def _crawl(result, spider):
deferred = process.crawl(spider)
deferred.addCallback(lambda results: print('waiting 5 seconds before restart...'))
deferred.addCallback(sleep, seconds=5)
deferred.addCallback(_crawl, spider)
return deferred
_crawl(None, 'demo')
process.start()
#代码参考来源:https://www.imooc.com/wenda/detail/605365