首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Python从入门到入土-网络爬虫(BeautifulSoup、lxml解析网页、requests获取网页)

Python从入门到入土-网络爬虫(BeautifulSoup、lxml解析网页、requests获取网页)

作者头像
共饮一杯无
发布2022-11-28 15:48:03
发布2022-11-28 15:48:03
1.3K0
举报

CSDN话题挑战赛第2期 参赛话题:学习笔记

BeautifulSoup

获取所有p标签里的文本

代码语言:javascript
复制
# 获取所有p标签里的文本

# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup

# 在此实现代码
def fetch_p(html):
    soup = BeautifulSoup(html, 'lxml')
    p_list = soup.find_all("p")
    results = [p.text for p in p_list]
    return results

if __name__ == '__main__':
    html = '''
        <html>
            <head>
                <title>这是一个简单的测试页面</title>
            </head>
            <body>
                <p class="item-0">body 元素的内容会显示在浏览器中。</p>
                <p class="item-1">title 元素的内容会显示在浏览器的标题栏中。</p>
            </body>
        </html>
        '''
    p_text = fetch_p(html)
    print(p_text)

BeautifulSoup 获取text

代码语言:javascript
复制
# BeautifulSoup 获取text
#
# 获取网页的text

# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup

# 在此实现代码
def fetch_text(html):
    soup = BeautifulSoup(html, 'lxml')
    result = soup.text
    return result

if __name__ == '__main__':
    html = '''
        <html>
            <head>
                <title>这是一个简单的测试页面</title>
            </head>
            <body>
                <p class="item-0">body 元素的内容会显示在浏览器中。</p>
                <p class="item-1">title 元素的内容会显示在浏览器的标题栏中。</p>
            </body>
        </html>
        '''
    text = fetch_text(html)
    print(text)

查找网页里所有图片地址

代码语言:javascript
复制
# 查找网页里所有图片地址

from bs4 import BeautifulSoup


# 在此实现代码
def fetch_imgs(html):
    soup = BeautifulSoup(html, 'html.parser')
    imgs = [tag['src'] for tag in soup.find_all('img')]
    return imgs

def test():
    imgs = fetch_imgs(
        '<p><img src="http://example.com"/><img src="http://example.com"/></p>')
    print(imgs)

if __name__ == '__main__':
    test()

lxml解析网页

使用xpath获取所有段落的文本

代码语言:javascript
复制
# 使用xpath获取所有段落的文本

# -*- coding: UTF-8 -*-
from lxml import etree

# 在此实现代码
def fetch_text(html):
    html = etree.HTML(html)
    result = html.xpath("//p/text()")
    return result

if __name__ == '__main__':
    html = '''
        <html>
            <head>
                <title>这是一个简单的测试页面</title>
            </head>
            <body>
                <p class="item-0">body 元素的内容会显示在浏览器中。</p>
                <p class="item-1">title 元素的内容会显示在浏览器的标题栏中。</p>
            </body>
        </html>
        '''
    imgs = fetch_text(html)
    print(imgs)

使用xpath获取所有的文本

代码语言:javascript
复制
# 使用xpath获取所有的文本

# -*- coding: UTF-8 -*-
from lxml import etree

# 在此实现代码
def fetch_text(html):
    html = etree.HTML(html)
    result = html.xpath("//text()")
    return result


if __name__ == '__main__':
    html = '''
        <html>
            <head>
                <title>这是一个简单的测试页面</title>
            </head>
            <body>
                <p>body 元素的内容会显示在浏览器中。</p>
                <p>title 元素的内容会显示在浏览器的标题栏中。</p>
            </body>
        </html>
        '''
    imgs = fetch_text(html)
    print(imgs)

使用xpath获取 class 为 “item-1” 的段落文本

代码语言:javascript
复制
# 使用xpath获取 class 为 "item-1" 的段落文本

# -*- coding: UTF-8 -*-
from lxml import etree

# 在此实现代码
def fetch_text(html):
    html = etree.HTML(html)
    result = html.xpath("//p[@class='item-1']/text()")
    return result


if __name__ == '__main__':
    html = '''
        <html>
            <head>
                <title>这是一个简单的测试页面</title>
            </head>
            <body>
                <p class="item-0">body 元素的内容会显示在浏览器中。</p>
                <p class="item-1">title 元素的内容会显示在浏览器的标题栏中。</p>
            </body>
        </html>
        '''
    imgs = fetch_text(html)
    print(imgs)

requests 获取网页

获取url对应的网页HTML

代码语言:javascript
复制
# 获取url对应的网页HTML

# -*- coding: UTF-8 -*-
import requests

# 在此实现代码
def get_html(url):
    response = requests.get(url=url)
    result = response.text
    return result

if __name__ == '__main__':
    url = "http://www.baidu.com"
    html = get_html(url)
    print(html)

requests 获取网页 with headers

代码语言:javascript
复制
# 将url对应的网页下载到本地

# -*- coding: UTF-8 -*-
import requests

def get_html(url, headers=None):
    response = requests.get(url=url)
    return response.text

if __name__ == '__main__':
    # 正确编写 headers
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36"
    }
    url = "http://www.baidu.com"
    html = get_html(url, headers)
    print(html)

requests post 请求

代码语言:javascript
复制
# requests post 请求

# -*- coding: UTF-8 -*-
import requests

# 在此实现代码
def get_response(url, data, headers=None):
    response = requests.post(url, data, headers)
    result = response.text
    return result

if __name__ == '__main__':
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36"
    }
    data = {
        "key1": "value1",
        "key2": "value2"
    }
    url = "http://httpbin.org/post"
    html = get_response(url, data, headers)
    print(html)

本文内容到此结束了, 如有收获欢迎点赞👍收藏💖关注✔️,您的鼓励是我最大的动力。 如有错误❌疑问💬欢迎各位指出。 主页共饮一杯无的博客汇总👨‍💻 保持热爱,奔赴下一场山海。🏃🏃🏃

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-09-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • BeautifulSoup
    • 获取所有p标签里的文本
    • BeautifulSoup 获取text
    • 查找网页里所有图片地址
  • lxml解析网页
    • 使用xpath获取所有段落的文本
    • 使用xpath获取所有的文本
    • 使用xpath获取 class 为 “item-1” 的段落文本
  • requests 获取网页
    • 获取url对应的网页HTML
    • requests 获取网页 with headers
    • requests post 请求
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档