Python网络爬虫的网站实例

本文介绍了使用Python进行网页爬取的基本方法,包括获取不同网站的HTML源代码、搜索关键词、下载图片及查询IP地址等操作。
该文章已生成可运行项目,

1.通过爬取网页源代码

import requests
def getHTMLText(url):
    try:
        r=requests.get(url,timeout=30)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        return "产生异常"

if __name__=="__main__":
    url="http://www.sdust.edu.cn"
    print(getHTMLText(url))

2.爬取京东商品的源代码

import requests
url="https://item.jd.com/5181380.html"
try:
    r=requests.get(url)
    r.raise_for_status()
    r.encoding=r.apparent_encoding
    print(r.text[:1000])
except:
    print("爬取失败")

3.爬取亚马逊商品的源代码

import requests

url="https://www.amazon.cn/gp/product/B071SDP8PC"

try:
    kv={'user-agent':'Mozilla/5.0'}
    r=requests.get(url,headers=kv)
    r.raise_for_status
    r.encoding=r.apparent_encoding
    print(r.text[24440:25145])
except:
    print("爬取失败")

4.百度、360搜索关键词

import requests

keyword="Python"
url="https://wwww.baidu.com/s"

try:
    kv={'wd':keyword}
    r=requests.get(url,params=kv)
    print(r.request.url)
    r.raise_for_status()
    print(len(r.text))
except:
    print("爬取失败")

import requests

keyword="Python"
kv={'q':keyword}
url="http://www.so.com/s"

try:
    r=requests.get(url,params=kv)
    print(r.request.url)
    r.raise_for_status()
    print(len(r.text))
except:
    print("爬取失败")
    

5.网络图片的爬取与下载

import requests
import os
url="http://image.nationalgeographic.com.cn/2017/0730/20170730125917668.jpg"
root="E://Python//wordplace//getHTMLText//picture//"
path=root + url.split('/')[-1]

try:
    if not os.path.exists(root):
        os.mkdir(root)
    if not os.path.exists(path):
        r=requests.get(url)
        with open(path,'wb') as f:
            f.write(r.content)
            f.close()
            print("文件保存成功")
    else:
        print("文件已存在")
except:
    print("爬取失败")

6.查询IP地址

import requests
url="http://m.ip138.com/ip.asp?ip="
try:
    r=requests.get(url+'202.204.80.112')
    r.raise_for_status()
    r.encoding=r.apparent_encoding
    print(r.text[-500:])
except:

    print("爬取失败")



本文章已经生成可运行项目
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mind_programmonkey

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值