首页 > 其他分享 >爬虫_02days

爬虫_02days

时间:2024-02-20 15:11:22浏览次数:27  
标签:soup res 爬虫 02days html 标签 print find

免费代理池搭建

# 代理有免费和收费代理
# 代理有http代理和https代理
# 匿名度
-高匿:隐藏访问者ip
-透明:服务端能拿到访问者ip
-作为后端,如何拿到使用代理人的ip
-请求头中:x-forword-for
-如果一个 HTTP 请求到达服务器之前,经过了三个代理 Proxy1、Proxy2、Proxy3,IP 分别为 IP1、IP2、IP3,用户真实 IP 为 IP0,那么按照 XFF 标准,服务端最终会收到以下信息:
X-Forwarded-For: IP0, IP1, IP2
-如果拿IP3,remote-addr中


# 搭建免费代理池:https://github.com/jhao104/proxy_pool
-使用python---》爬取免费的代理---》解析出ip和端口,地区---》存到库中
-使用flask---》搭建了一个web服务--》只要向 /get 发送一个请求,他就随机返回一个代理ip



# 步骤:
1 把项目下载下来,pycharm打开https://github.com/jhao104/proxy_pool
2 安装依赖,虚拟环境
3 修改配置文件
DB_CONN = 'redis://127.0.0.1:6379/2'
4 启动爬虫:python proxyPool.py schedule
5 启动web服务:python proxyPool.py server

6 以后访问:http://127.0.0.1:5010/get/

7 使用代码
import requests
res=requests.get('http://192.168.1.252:5010/get/?type=http').json()
print(res['proxy'])

代理池使用

# 使用django写个项目---》只要一访问,就返回访问者ip

# 编写步骤
1 编写django项目,写一个视图函数
def index(request):
    ip=request.META.get('REMOTE_ADDR')
    return HttpResponse('您的ip 是:%s'%ip)

2 配置路由:
    from app01.views import index
    urlpatterns = [
        path('', index),
    ]
3 删除settings.py 中的数据库配置

4 把代码上传到服务端,运行djagno项目
python3.8 manage.py runserver 0.0.0.0:8080

5 本地测试:
import requests
res=requests.get('http://127.0.0.1:5010/get/?type=http').json()
print(res['proxy'])
res1=requests.get('http://47.113.229.151:8080/',proxies={'http':res['proxy']})
print(res1.text)

爬取某视频网站

import requests
import re

res = requests.get('https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=1&start=0')
# print(res.text)
# 解析出所有视频地址---》re解析
video_list = re.findall('<a href="(.*?)" class="vervideo-lilink actplay">', res.text)
# print(video_list)
for video in video_list:
    real_url = 'https://www.pearvideo.com/' + video
    video_id = video.split('_')[-1]
    # print('视频详情地址是:', real_url)
    # 向能返回mp4地址的接口发送请求:https://www.pearvideo.com/videoStatus.jsp?contId=1706684&mrd=0.05520583472057039
    # 直接发送请求,返现返回的结果中,没有mp4地址,但是在它的页面中就有
    # 必须携带referer,referer是视频详情地址
    # contId  是视频id号
    header={
        'Referer':real_url
    }
    res = requests.get('https://www.pearvideo.com/videoStatus.jsp?contId=%s&mrd=0.05520583472057039'%video_id,headers=header)
    # print(res.json())
    real_mp4_url=res.json()['videoInfo']['videos']['srcUrl']
    # print(real_mp4_url) # 视频不能播放
    mp4 = real_mp4_url.replace(real_mp4_url.split('/')[-1].split('-')[0], 'cont-%s' % video_id)
    print('能播放的视频地址:',mp4)

    # 把视频下载到本地
    res=requests.get(mp4)
    with open('./video/%s.mp4'%video_id,'wb') as f:
        for line in res.iter_content():
            f.write(line)
            
            
            
            
            
 '''
 注意:
 1 发送ajax请求,获取真正视频地址
 2 发送ajax请求时,必须携带referer
 3 返回的视频地址,需要处理后才能播放
 '''

爬取新闻

# 解析库:汽车之家
# bs4 解析库  pip3 install beautifulsoup4

import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.autohome.com.cn/news/1/#liststart')
# print(res.text)
# 第一个参数,是要总的字符串
# 第二个参数,使用哪个解析库 :html.parser:内置的,不需要额外安装,速度慢一些      lxml:额外安装lxml  pip3 install lxml
soup = BeautifulSoup(res.text, 'html.parser')
# 查找  标签
# 1 找到所有 类名是article 的ul标签
ul_list = soup.find_all(name='ul', class_='article')
# print(len(ul_list))

# 2 循环每个ul---》找出每个ul内部的所有li
for ul in ul_list:
    li_list = ul.find_all(name='li')
    # print(li_list)
    for li in li_list:  # 查找每个li标签中得
        h3 = li.find(name='h3')
        if h3:
            # 拿出h3标签的文本内容
            title = h3.text
            content=li.find('p').text # 第一个参数就是name
            # 标签对象 .attrs 拿到标签的所有属性,只要属性中得href
            url='https:'+li.find(name='a').attrs['href']
            # 可以不用 .attrs  直接取属性也可以
            img=li.find('img')['src']
            print('''
            文章标题:%s
            文章摘要:%s
            文章url:%s
            文章图片:%s
            ''' % (title,content,url,img))

            # 1 所有图片下载到本地
            # 2 在mysql中创建一个表 article---》id,title,content,url,img--->把爬回来的数据,存到数据库--》pymysql

bs4介绍和遍历文档树

# bs4是解析 xml/html 格式字符串的解析库
-不但可以解析(爬虫),还可以修改

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_xx' xx='zz'>lqz <b>The Dormouse's story <span>彭于晏</span></b>  xx</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
# soup=BeautifulSoup(html_doc,'html.parser')
soup = BeautifulSoup(html_doc, 'lxml')  # pip3 install lxml

# 1 文档容错能力
# res=soup.prettify()
# print(res)

# 2 遍历文档树: 文档树:html开头 ------html结尾,中间包含了很多标签
# 通过  . 查找标签
# print(soup.html.head.title)

# 3 通过 . 找到p标签  只能找到最先找到的第一个
# print(soup.html.body.p)
# print(soup.p)

# 4 获取标签的名称
# p = soup.html.body.p
# print(p.name)

# 5 获取标签的属性
# p = soup.html.body.p
# print(p.attrs.get('class')) # class 特殊,可能有多个,所以放在列表汇总
# print(soup.a.attrs.get('href'))
# print(soup.a['href'])

# 6 获取标签的文本内容
# 6.1  标签对象.text  # 拿标签子子孙孙
# 6.2  标签对象.string # 该标签有且只有自己有文本内容才能拿出来
# 6.3  标签对象.strings # 拿子子孙孙,都放在生成器中
# print(soup.html.body.p.b.text)
# print(soup.html.body.p.text)
# print(soup.html.body.p.string) # 不能有子 孙
# print(soup.html.body.p.b.string) # 有且只有它自己

# print(soup.html.body.p.strings) # generator 生成器---》把子子孙孙的文本内容都放在生成器中,跟text很像
# print(list(soup.html.body.p.strings)) # generator 生成器---》把子子孙孙的文本内容都放在生成器中,跟text很像


# 7 嵌套选的
# soup.html.body


# -----了解-----------
# 8 子节点、子孙节点
# print(soup.p.contents) # p下所有子节点,只拿直接子节点


# print(soup.p.children) # 直接子节点 得到一个迭代器,包含p下所有子节点
# for i,child in enumerate(soup.p.children):
#     print(i,child)


# print(soup.p.descendants) #获取子孙节点,p下所有的标签都会选择出来  generator
# for i,child in enumerate(soup.p.descendants):
#     print(i,child)

#9、父节点、祖先节点
# print(soup.a.parent) #获取a标签的父节点

# print(list(soup.a.parents)) #找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...

#10、兄弟节点
# print(soup.a.next_sibling) #下一个兄弟
# print(soup.a.previous_sibling) #上一个兄弟

print(list(soup.a.next_siblings)) #下面的兄弟们=>生成器对象
print(soup.a.previous_siblings) #上面的兄弟们=>生成器对象

'''
#1、用法  .
#2、获取标签的名称
#3、获取标签的属性
#4、获取标签的内容
#5、嵌套选择
#6、子节点、子孙节点
#7、父节点、祖先节点
#8、兄弟节点

'''

搜索文档树

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my_p" class="title"><b id="bbb" class="boldest">The Dormouse's story</b>
</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_doc, 'lxml')

# find:找第一个   和find_all:找所有
# 五种过滤器: 字符串、正则表达式、列表、True、方法
# 1 字符串  查找条件是字符串
# res=soup.find(id='my_p')
# res=soup.find(class_='boldest')
# res=soup.find(href='http://example.com/elsie')
# res=soup.find(name='a',href='http://example.com/elsie',id='link1',class_='sister') # 多个是and条件
# 可以写成
# res=soup.find(attrs={'href':'http://example.com/elsie','id':'link1','class':'sister'})
# print(res)


#2  正则表达式
# import re
# res=soup.find_all(href=re.compile('^http'))
# res=soup.find_all(name=re.compile('^b'))
# res=soup.find_all(name=re.compile('^b'))
# print(res)


# 3 列表
# res=soup.find_all(name=['body','b','a'])
# res=soup.find_all(class_=['sister','boldest'])
# print(res)

# 4 布尔
# res=soup.find_all(id=True)
# res=soup.find_all(name='img',src=True)
# print(res)


# 5 方法
# def has_class_but_no_id(tag):
#     return tag.has_attr('class') and not tag.has_attr('id')
# print(soup.find_all(has_class_but_no_id))


# 6 搜索文档树可以结合遍历文档树一起用-->拿标签的属性,文本,之前都讲过

# res=soup.html.body.find_all('p')
# res=soup.find_all('p')
# print(res)

# 7 find 和find_all的区别:find 就是find_all,只要第一个


# 8 recursive=True   limit=1
# res=soup.find_all(name='p',limit=2) # 限制条数
res=soup.html.body.find_all(name='p',recursive=False) # 是否递归查找
print(res)

css选择器

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my_p" class="title"><b id="bbb" class="boldest">The Dormouse's story</b>
</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'lxml')
# css 选择器
'''
.类名
#id
body
body a

# 终极大招:css选择器,复制

'''
# res=soup.select('a.sister')
# res=soup.select('p#my_p>b')
# res=soup.select('p#my_p b')
# print(res)


import requests
from bs4 import BeautifulSoup
header={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
res=requests.get('https://www.zdaye.com/free/',headers=header)
# print(res.text)
soup=BeautifulSoup(res.text,'lxml')
res=soup.select('#ipc > tbody > tr:nth-child(2) > td.mtd')
print(res[0].text)

 

标签:soup,res,爬虫,02days,html,标签,print,find
From: https://www.cnblogs.com/wzh366/p/18023161

相关文章

  • 爬虫——day01
    爬虫介绍爬虫是什么? -通过编程技术---》把互联网中的数据---》获取到---》数据清洗---》存到库中python:request,selenium---》app,小程序,网站---》xpaht,lxml---》mysql,redis,文件,excel,mongodb-通过编程语言---》模拟发送http请求---》获取数据---》解析--》入库......
  • 【60行代码解决】2024年最新版python爬虫有道翻译js逆向
    一、表单参数sign加密sign:c0f36866a9c650144ed5bac4eba532a7这种32位一般是MD5加密1.搜索sign:2.点击去分别在每个**sign:某某某**处打上断点结果在这个断点断住了3.原代码constu="fanyideskweb",d="webfanyi"functionj(e){returnc.a.createHash......
  • 第 8章 Python 爬虫框架 Scrapy(下)
    第8章Python爬虫框架Scrapy(下)8.1Scrapy对接Selenium有一种反爬虫策略就是通过JS动态加载数据,应对这种策略的两种方法如下:分析Ajax请求,找出请求接口的相关规则,直接去请求接口获取数据。使用Selenium模拟浏览器渲染后抓取页面内容。8.1.1如何对接单独使用Sc......
  • 爬虫案例
    多进程和多线程爬虫案例importos.pathimporttimefrommultiprocessingimportProcessfromthreadingimportThreadimportrequestsfromlxmlimportetreefromfake_useragentimportUserAgentclassBaseSpider(object):def__init__(self):self.url......
  • 爬虫_060_urllib post请求百度翻译的详细翻译
    目录百度翻译详细翻译接口关于复制的小技巧复制浏览器全部的requestheader代码百度翻译详细翻译接口这个接口,是我上一次用的接口,MD。关于复制的小技巧这个接口的参数数据就比较多了,我们都需要构建到data对象当中。这里可以第一步,先复制数据,然后粘贴到sublime当中。第二步......
  • 爬虫_059_urllib post请求百度翻译
    目录分析百度翻译找接口编写代码需要注意的点修改代码返回数据解析最后的说明分析百度翻译找接口编写代码importurllib.requestimporturllib.parseheaders={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)......
  • 爬虫_058_urllib get请求的urlencode方法
    目录urllib.parse.urlencode()quote方法使用的不是很经常的。因为quote的作用是将汉字转为百分号编码后的ASCII字符串。如果你的路径当中只有一个参数,你这样使用quote拼接一下url,这是没有问题的。如果你的路径当中有多个参数,并且参数都是中文的,你还使用quote,就TMD懵逼了。......
  • 爬虫_057_urllib get请求的quote方法
    目录引子编码集的演变需求知识点重新测试get请求方式的quote方法引子将百度搜索周杰伦的地址栏地址,复制到pycharm当中变成下面的样子:https://www.baidu.com/s?wd=%E5%91%A8%E6%9D%B0%E4%BC%A6编码集的演变ASCII编码:一个字符一个字节中国:GB2312日本:Shift_JIS韩国:Euc-k......
  • 爬虫_056_urllib请求对象的定制
    目录url组成第一个反爬-UA校验制造一个UA请求对象的定制url组成协议httphttps主机www.baidu.com端口号http80https443mysql3306oracle1521redis6379mongodb27017路径参数?号锚点#号第一个反爬-UA校验制造一个UA从浏览器......
  • 爬虫_055_urllib下载
    目录下载网页下载图片下载视频总结下载网页下载图片下载视频总结真的,没有什么含金量,就是找到资源的地址,然后使用urllib.request.urlretrieve()就可以了。......