먼저 머리를 먼저 가져 오기 라이브러리 :
import os
import requests
from pyquery import PyQuery as pq
import pymysql # 用于连接并操作MySQL数据库
각 사이트의 사용자 에이전트, 예를 들어, 사전에 사용자 에이전트를 찾기 위해 웹 사이트를 열 필요가 다른 머리의 도입은, 내가 웹 사이트에 대한 정보를 크롤링 : HTTPS : //www.icourse163.org/university/view/all.htm# / 빨간색 원 부분을 찾아, 네트워크 클릭 볼 수있는 파이어 폭스 열려있는 요소를 마우스 오른쪽 단추로 클릭
한 다음 코드를 삽입합니다 :
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3423.2 Safari/537.36'
}
그런 다음 응답 요청을 보낼 주로 검색 기능을 쓰기 :
def search():
url = 'https://www.icourse163.org/university/view/all.htm#/'
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
except requests.ConnectionError:
return None
원하는 정보를 얻기 위해 기록 위치이다 :
def get_image(html):
doc = pq(html)
items = doc('.g-flow .u-usitys .u-usity ').items() # 如果不加.items(),items就不是pyquery对象
for item in items:
yield {
'title': item.find('img').attr('alt'),
'image': item.find('img').attr('src')
}
: 요소를보고, 작은 파트너가 해당 정보를 마우스 오른쪽 버튼으로 클릭, 그러한 정보의 위치를 찾는 방법을 알고 파이어 폭스와 사이트가 열리지 않습니다가있을 수 있습니다
그런 다음 사진을 저장하는 함수를 작성 :
def save_image(item):
file_path_all = 'D:/python-pro/partners'#存储图片的本地地址
if not os.path.exists(file_path_all):
os.makedirs(file_path_all)
try:
response = requests.get(item.get('image'))
if response.status_code == 200:
file_path = '{0}/{1}.{2}'.format(file_path_all, item.get('title'), 'jpg') # 以图片名字命名的话,可能会有重复的,造成图片丢失
if not os.path.exists(file_path):
with open(file_path, 'wb') as f:
f.write(response.content)
else:
print('Already Download', file_path)
except requests.ConnectionError:
print('Failed to Save Image')
마지막으로, 주요 기능을 쓰기 :
def main():
connection = pymysql.connect(host='localhost', # 连接数据库
user='root',
password='', # 你安装mysql时设置的密码
db='test2',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
sql = "insert into partners(name,url,parId)values(%s,%s,%s)"
try:
html = search()
cursor = connection.cursor()
i = 1
for item in get_image(html):
print([i]+[item])
save_image(item)
cursor.execute(sql, (item['title'], item['image'], i))
connection.commit()
i += 1
finally:
connection.close()
return None
if __name__ == '__main__':
main()
: 결과는 다음입니다
로컬 그림으로 :
데이터베이스에 저장된 데이터 :
마지막으로 모든 코드를 첨부 :
import os
import requests
from pyquery import PyQuery as pq
import pymysql # 用于连接并操作MySQL数据库
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3423.2 Safari/537.36'
}
def search():
url = 'https://www.icourse163.org/university/view/all.htm#/'
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
except requests.ConnectionError:
return None
def get_image(html):
doc = pq(html)
items = doc('.g-flow .u-usitys .u-usity ').items() # 如果不加.items(),items就不是pyquery对象
for item in items:
yield {
'title': item.find('img').attr('alt'),
'image': item.find('img').attr('src')
}
def save_image(item):
file_path_all = 'D:/python-pro/partners'#存储图片的本地地址
if not os.path.exists(file_path_all):
os.makedirs(file_path_all)
try:
response = requests.get(item.get('image'))
if response.status_code == 200:
file_path = '{0}/{1}.{2}'.format(file_path_all, item.get('title'), 'jpg') # 以图片名字命名的话,可能会有重复的,造成图片丢失
if not os.path.exists(file_path):
with open(file_path, 'wb') as f:
f.write(response.content)
else:
print('Already Download', file_path)
except requests.ConnectionError:
print('Failed to Save Image')
def main():
connection = pymysql.connect(host='localhost', # 连接数据库
user='root',
password='', # 你安装mysql时设置的密码
db='test2',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
sql = "insert into partners(name,url,parId)values(%s,%s,%s)"
try:
html = search()
cursor = connection.cursor()
i = 1
for item in get_image(html):
print([i]+[item])
save_image(item)
cursor.execute(sql, (item['title'], item['image'], i))
connection.commit()
i += 1
finally:
connection.close()
return None
if __name__ == '__main__':
main()
주의 사항 :
- 이 코드는 데이터베이스 서버 이름에 연결하려면 자신의 데이터베이스 이름을 변경하거나 연결에없는되어야한다
- 사전 pyquery 라이브러리에 설치하려면 파이썬 기본값은 수동으로 설치할 필요가 없습니다;
- 적절한 크롤링 클래스 이름 정보를 식별하거나 오류가있을 것이다;
- 이 코드는 학습을위한 것입니다.