|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
有没有大哥教一下如何爬百度上的许嵩图片
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)
find_picture=re.compile(r'href="/image/search?(.*?)""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)
return html
def getData(url):
html=askurl(url)
soup = BeautifulSoup(html, "html.parser")
html=str(html)
picture= re.findall(find_picture,html)
print(picture)
if __name__=="__main__":
main()
我这好像很多问题,尤其是正则表达式那里,感觉写不出来合适的。系统给的结果是可以执行,但并没有执行print(picture)这一步
正则没写对呀,当然没结果
- 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()
复制代码
|
|