url="https://item.jd.com/100012881854.html" kv = {'user-agent':'Mozilla/5.0'} r = requests.get(url,headers = kv) print(r.status_code) print(r.encoding) print(r.text[:1000])
200
utf-8
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<!--yushou-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>【魅族17 Pro】魅族17 Pro 8GB+128GB 定白 骁龙865 旗舰5G手机 27W无线充 6400W后置主摄 90Hz屏幕 支持NFC 智能游戏手机【行情 报价 价格 评测】-京东</title>
<meta name="keywords" content="MEIZU17 Pro,魅族17 Pro,魅族17 Pro报价,MEIZU17 Pro报价"/>
<meta name="description" content="【魅族17 Pro】京东JD.COM提供魅族17 Pro正品行货,并包括MEIZU17 Pro网购指南,以及魅族17 Pro图片、17 Pro参数、17 Pro评论、17 Pro心得、17 Pro技巧等信息,网购魅族17 Pro上京东,放心又轻松" />
<meta name="format-detection" content="telephone=no">
<meta http-equiv="mobile-agent" content="format=xhtml; url=//item.m.jd.com/product/100012881854.html">
<meta http-equiv="mobile-agent" content="format=html5; url=//item.m.jd.com/product/100012881854.html">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="canonical" href="//item.jd.com/100012881854.html"/>
<link rel="dns-prefetch" href="//misc.360buyimg.com"/>
<link rel="dns-prefetch" href="//s
必须加kv,不然
这是无法访问的
回到京东界面
因此
kv = {'user-agent':'Mozilla/5.0'} r = requests.get(url,headers = kv)
通过更改User-Agent字段就可以轻易骗过该网站。
import requests def getHtmlText(url): try: kv = {'user-agent': 'Mozilla/5.0'} r = requests.get(url, headers=kv) r.raise_for_status() r.encoding = r.apparent_encoding return r.text[:500] except: return '爬取失败' if __name__ == '__main__': url='https://item.jd.com/100012885246.html' print(getHtmlText(url))
可以更换url,爬取不同网页信息