步骤:
-
导入必要的requests和re库。
-
使用requests库获取淘宝搜索页面的代码内容,其中使用curl.trillworks.com神器访问页面源码
-
使用re库对搜索页面中的内容进行搜索匹配,获取想要的商品名称和价格信息
-
将获取的信息全部打印出来
设置请求头header,这样才可以伪装成浏览器
用谷歌浏览器打开淘宝,用关键词“手机”搜索后,按F12进入检查,查看Network,选中第一行,右击选中“copy as cURL(bash),然后讲复制到的信息粘贴到https://curl.trillworks.com/,网页将自动生成requests表头和参数信息。
将生成的headers={ } 这块信息复制到我们要编写的代码中,赋值给一个变量,将该变量作为requests.get()的表头参数,这样就可以访问淘宝搜索页面的表头信息了。
import requests
import re
def getHTMLText(url):
f_headers = {
'authority': 's.taobao.com',
'cache-control': 'max-age=0',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36',
'sec-fetch-user': '?1',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',