鍙互浣跨敤Python鐨剅equests搴撴潵鍙戦丠TTP璇锋眰鑾峰彇缃戦〉鍐呭銆傜劧鍚庨氳繃姝e垯琛ㄨ揪寮忔垨鑰匓eautifulSoup绛夊伐鍏蜂粠HTML涓彁鍙栨墍闇鏁版嵁銆傛渶鍚庡皢鎻愬彇鍒扮殑鏁版嵁瀛樺叆MySQL鏁版嵁搴撱

涓嬮潰鏄竴涓ず渚嬩唬鐮侊細

python
import requests
import re
from bs4 import BeautifulSoup
import pymysql.cursors

# 瀹氫箟瑕佽闂殑URL
url = "http://example.com"

# 鍙戦丟ET璇锋眰鑾峰彇缃戦〉鍐呭
response = requests.get(url)
html_content = response.text

# 浣跨敤姝e垯琛ㄨ揪寮忔彁鍙栨墍闇淇℃伅锛堣繖閲屽彧浣滀负绀轰緥锛
pattern = r'<div class="title">(.*?)</div>'
titles = re.findall(pattern, html_content)

# 杩炴帴MySQL鏁版嵁搴
connection = pymysql.connect(host='localhost', user='root', password='password', db='database')
cursor = connection.cursor()

try:
    # 閬嶅巻鎻愬彇鍒扮殑鏍囬鍒楄〃锛屽苟灏嗗叾鎻掑叆鏁版嵁搴
    for title in titles:
        sql = "INSERT INTO table (column1) VALUES ('%s');" % title
        cursor.execute(sql)
    
    # 鎻愪氦浜嬪姟
    connection.commit()
except Exception as e:
    print("Error:", str(e))
finally:
    # 鍏抽棴鏁版嵁搴撹繛鎺
    cursor.close()
    connection.close()

浠ヤ笂灏辨槸python requests 鐖彇骞舵彁鍙栧唴瀹瑰啓鍏ysql鐨勮缁嗗唴瀹癸紝鏇村淇℃伅璇峰叧娉∣D浜戝叾瀹冪浉鍏虫枃绔狅紒



鏈枃URL锛http://www.odweb.cn/news_show.html?id=211