• 爬虫学习日记


    引言:

    1.语言:python

    2.预备知识——python:爬虫学习前记----Python-CSDN博客

    3.学习资源:【Python+爬虫】

    html:

    1. html>
    2. <html>
    3. <head>
    4. <title>czy_demotitle>
    5. <meta charset="UTF-8">
    6. head>
    7. <body>
    8. <h1>一级标题(h1~h6)h1>
    9. <p>普通文本<b>加粗b><i>斜体i><u>下划线u>p>
    10. <img src="1.jpg" width="500px">
    11. <br><a href="http://t.csdnimg.cn/DvHJ6" target="_blank">CSDN链接a>
    12. <p>这是多个span展示:<span style="background-color: bisque">span1span><span style="background-color: aquamarine">span2span>p>
    13. <ol>
    14. <li>有序列表li>
    15. <li>有序列表li>
    16. <li>有序列表li>
    17. ol>
    18. <ul>
    19. <li>无序列表li>
    20. <li>无序列表li>
    21. <li>无序列表li>
    22. ul>
    23. <table border="1">
    24. <thead>
    25. <tr>头部有几个就写几行trtr>
    26. <tr>第二行头部标签tr>
    27. thead>
    28. <tbody>
    29. <tr>
    30. <td>第一行*单元格1td>
    31. <td>第一行*单元格2td>
    32. <td>第一行*单元格3td>
    33. tr>
    34. <tr>
    35. <td>第二行*单元格1td>
    36. <td>第二行*单元格2td>
    37. <td>第二行*单元格3td>
    38. tr>
    39. tbody>
    40. table>
    41. body>
    42. html>

    爬虫代码

    1.两个需要的包

    1. from bs4 import BeautifulSoup
    2. import requests

    2.爬原代码

    1. response = requests.get('http:.......')
    2. print(response) # 响应
    3. print(response.status_code) # 状态码---200[ok]
    4. print(response.text) # 打印源码

    3.爬指定的内容

    1. response = requests.get('http:........')
    2. content =response.text
    3. soup = BeautifulSoup(content,"html.parser") # 解析器html
    4. all_p=soup.findAll("p",attrs={"class":""})
    5. for p in all_p:
    6. print(p.string)
    7. all_p=soup.findAll("h3")
    8. for p in all_p:
    9. p1=p.findAll("a")
    10. for p2 in p1:
    11. print(p2.string)

    3.下载图片

    1. from bs4 import BeautifulSoup
    2. import requests
    3. headers={
    4. 'User-Agent': 【替换成目标网页的User-Agent】
    5. }
    6. response = requests.get('http://data.shouxi.com/item.php?id=1239786',headers=headers)
    7. response.encoding = 'GBK'
    8. response.encoding = 'utf-8'
    9. soup = BeautifulSoup(response.text,"html.parser") # 解析器html
    10. # print(response.text)
    11. i=soup.findAll("img")
    12. num=1;
    13. for Img in i:
    14. img_url=Img.get("src")
    15. if not img_url.startswith('http:'):
    16. img_url="http:....【替换成网页地址】"+img_url # 将相对地址转换成绝对地址
    17. # 发送请求下载图片
    18. img_response = requests.get(img_url, headers=headers)
    19. with open(f'image.{num}.jpg', mode='wb') as f:
    20. f.write(img_response.content)
    21. print(f'图片已保存: images.{num}')
    22. num = num + 1
  • 相关阅读:
    [pytest] requests模块
    一篇文章就足够解决大数据实时面试
    java计算机毕业设计惠购网站MyBatis+系统+LW文档+源码+调试部署
    Betaflight关于STM32F405 SBUS协议兼容硬件电气特性问题
    【DTEmpower案例操作教程】智能模型预警
    JVM学习08——JVM调优
    字符串数字出现的新功能
    要远离职场中的哪几类人
    华为HCIA学习(一)
    文娱行业搜索最佳实践
  • 原文地址:https://blog.csdn.net/wuhu_czy/article/details/140360967