爬虫常用笔记总结-创新互联

方法

创新互联公司-专业网站定制、快速模板网站建设、高性价比长治网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式长治网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖长治地区。费用合理售后完善,十多年实体公司更值得信赖。
import requests
from bs4 import BeautifulSoup
from fake_useragent import FakeUserAgent

hd = {'User-Agent': FakeUserAgent().random}
r = requests.get('https://www.meishij.net/fenlei/zaocan/', headers=hd)
# r.status_code   # 查看状态
# r.encoding  # 编码 ISO-8859-1
r.encoding = 'UTF-8'  # 转换编码格式
soup = BeautifulSoup(r.text, 'html.parser')  # r.content

"""

"""
# 指定标签
alst = soup.find_all('table')
for i in alst:
    print(i.a.get('title'), i.span.string, '\t', i.p.string)

# 指定样式 class_
info_all = soup.find_all('div', class_='list_s2_item')
for i in info_all:
    info1 = i.find('a', class_='list_s2_item_info').strong.string
    info2 = i.find('a', class_='list_s2_item_info').span.string

# 指定元素
address = soup.select(
    'body >div.comm-content-box.clearfloat >div >div.comm-content-left.clearfloat >div >div.xq_toggle >div:nth-child(2) >table:nth-child(1) >tbody >tr:nth-child(2) >td:nth-child(2)')
print(address[0].string)

"""
获取内容语法
data.get_text()   # 获取data中文本内容
p.string  #

张三

a.get('title') # title='张三' """

借用网站功能查IP地址:

import requests
from bs4 import BeautifulSoup
from fake_useragent import FakeUserAgent


def get_address_by_ip(ip):
    hd = {'User-Agent': FakeUserAgent().random}
    url = 'https://ip.hao86.com/' + ip + '/'
    r = requests.get(url, headers=hd)
    r.encoding = 'UTF-8'
    soup = BeautifulSoup(r.text, 'html.parser')
    address = soup.select(
        'body >div.comm-content-box.clearfloat >div >div.comm-content-left.clearfloat >div >div.xq_toggle >div:nth-child(2) >table:nth-child(1) >tbody >tr:nth-child(2) >td:nth-child(2)')
    return address[0].string


IP = input('输入你要查询的IP:')  # 221.218.142.209
address = get_address_by_ip(IP)
print(address)

保存图片:

import requests
import os

'''
爬取指定url图片
可能出现的问题:图片地址不合法,缺少http
http://upload.techweb.com.cn/s/310/2018/0410/1523330175838.jpg
'''
url4 = 'http://img.netbian.com/file/2022/1127/small1208244iXg61669522104.jpg'

theUrl = url4  # 指定要爬取的url

# 爬取到的图片存在电脑那个磁盘位置
root = "d://pythonZoneHH//pic2HH//"

path = root + theUrl.split("/")[-1]  # 这句话可以保证原来图片叫什么名字,爬下来时候还叫什么名字
print(path)
try:
    if not os.path.exists(root):  # 判断磁盘制定文件夹是否存在,
        os.makedirs(root)  # 如果不存在就创建文件夹

    r = requests.get(theUrl)
    print("文件大小", len(r.content) / 1024, "kb")
    with open(path, "wb") as f:
        print("正在保存文件...")
        f.write(r.content)  # 向文件中写入二进制内容
        print("文件保存成功")
except Exception as e:
    print("爬取失败", e)

页面中不存在的数据爬取:

右键检查,从网络的请求中的找到对应数据,在标头中复制出URL

import json

from bs4 import BeautifulSoup
import requests
from fake_useragent import FakeUserAgent

re_url = 'https://www.thecfa.cn/index.html'
url = 'https://www.thecfa.cn/nvzgjd/dataApi/text/v1?contId=30235&next=-1'
hd = {'User-Agent': FakeUserAgent().random, 'Referer': re_url}  # Referer:re_url 设置引用页
r = requests.get(url, headers=hd)
r.encoding = 'UTF-8'
# r.text 获取到的是一个字符串  {"text":" 国际足联排名..."}  类型:dic = json.loads(r.text)  # 字符串转json数据  用 json.loads(内容)
html_doc = dic.get('text')  # 通过 .get('键')  取出值即可
soup = BeautifulSoup(html_doc, 'html.parser')
info_all = soup.find_all('li')
for i in info_all:
    # print(i, '....')
    date = i.find('div', class_='date').get_text()
    img_url = i.find_all('div', class_='country')[0].p.img.get('src')
    score = i.find('div', class_='score').get_text()
    img_url2 = i.find_all('div', class_='country')[1].p.img.get('src')
    print(date, '\t', img_url, '\n', score, '\t', img_url2)

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧

网页标题:爬虫常用笔记总结-创新互联
链接分享:https://www.cdcxhl.com/article42/coisec.html

成都网站建设公司_创新互联,为您提供虚拟主机网站排名外贸建站微信小程序定制网站App开发

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网站建设