标题需求:获取script标签中的变量值
项目背景
在进行网页爬取时,有时候需要获取网页中的一些动态生成的数据,这些数据可能是通过JavaScript代码动态生成的。而这些JavaScript代码通常被包含在
目的:从网页的HTML源代码中提取出
思路:
我们将使用Python编写一个爬虫程序,通过解析HTML源代码,定位到
导入包:
import requests
from bs4 import BeautifulSoup
import re
解析js变量方法:
def get_js_var(self, html):
# 使用BeautifulSoup解析HTML源代码
soup = BeautifulSoup(html, "html.parser")
# 获取所有的<script>标签
script_tags = soup.find_all("script")
# 提取<script>标签中的JavaScript代码
javascript_code = []
for script_tag in script_tags:
code = script_tag.string
if code:
javascript_code.append(code)
# 使用正则表达式匹配变量值
pattern = r"var\s+(\w+)\s*=\s*(.*?);"
# 我这里是写了一个我需要默认值,可能有些页面并没有这个变量
variables = {'js_video_url': None}
for code in javascript_code:
matches = re.findall(pattern, code)
for match in matches:
variable_name = match[0]
variable_value = match[1]
variables[variable_name] = variable_value
return variables
方法调用:
# 发送GET请求,获取网页源代码
url = ""
response = requests.get(url)
html = response.text
# 获取JavaScript的变量,返回变量集合
jsObject = self.get_js_var(html=html)