正则没写对呀,当然没结果import urllib.request
import re
from bs4 import BeautifulSoup
def main():
url = "https://cn.bing.com/images/search?q=%E8%AE%B8%E5%B5%A9&form=HDRSC2&first=1&tsc=ImageBasicHover"
datalist = getData(url)
# 源码图片有两种格式
# <img class="mimg" style="background-color:#925839;color:#925839" height="182" width="182" src="https://tse4-mm.cn.bing.net/th/id/OIP-C.yTXj-rc8THlpAagM9o58TAHaHa?w=182&h=182&c=7&r=0&o=5&dpr=1.25&pid=1.7" alt="许嵩 的图像结果"/>
# <img class="mimg vimgld" style="background-color:#3c1d19;color:#3c1d19" height="188" width="134" data-src="https://tse1-mm.cn.bing.net/th/id/OIP-C.dKR_c0_6PDuIM_ewjq7vzQHaKY?w=134&h=188&c=7&r=0&o=5&dpr=1.25&pid=1.7" alt="许嵩 的图像结果"/>
find_picture = re.compile(
r'<img class="mimg.*?".*?src=(".*?") alt="许嵩 的图像结果"')
def askurl(url):
head = {
"User-Agent": " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.43"}
request = urllib.request.Request(url, headers=head)
html = ""
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
# print(html)
return html
def getData(url):
html = askurl(url)
soup = BeautifulSoup(html, "html.parser")
picture = re.findall(find_picture, html)
# for i in
print(picture, len(picture))
if __name__ == "__main__":
main()
|