javascript - 使用 python 抓取时访问数据层(JS 变量)

标签 javascript python python-2.7 web-scraping beautifulsoup

我正在使用漂亮的汤来抓取网页。我想访问此 webpage 上存在的数据层(一个 javascript 变量) ?如何使用 python 检索它? enter image description here

最佳答案

您可以在 rejson.loads 的帮助下从源代码中解析它,以找到包含 json 的正确 script 标签 :

from bs4 import BeautifulSoup
import re
from json import loads
url = "http://www.allocine.fr/video/player_gen_cmedia=19561982&cfilm=144185.html"

soup = BeautifulSoup(requests.get(url).content)

script_text = soup.find("script", text=re.compile("var\s+dataLayer")).text.split("= ", 1)[1]

json_data = loads(script_text[:script_text.find(";")])

运行它你会看到我们得到了你想要的:

In [31]: from bs4 import BeautifulSoup
In [32]: import re    
In [33]: from json import loads    
In [34]: import requests

In [35]: url = "http://www.allocine.fr/video/player_gen_cmedia=19561982&cfilm=144185.html"

In [36]: soup = BeautifulSoup(requests.get(url).content, "html.parser")

In [37]: script_text = soup.find("script", text=re.compile("var\s+dataLayer")).text.split("= ", 1)[1]

In [38]: json_data = loads(script_text[:script_text.find(";")])

In [39]: json_data
Out[39]: 
[{'actor': '403573,19358,22868,612492,418933,436500,46797,729453,66391,16893,211493,249636,18324,483703,1193,165792,231665,114167,139915,155111,258115,119842,610268,166263,597100,134791,520768,149470,734146,633703,684803,763372,673220,748361,178486,241328,517093,765381,693327,196630,758799,220756,550759,737383,263596,174710,118600,663153,463379,740361,702873,659451,779133,779134,779135,779136,779137,779138,779139,779140,779141,779142,779143,779144,779145,779146,779147,779241,779242,779243,779244',
  'director': '41198',
  'genre': '13025=action&13012=fantastique',
  'movie_distributors': 929,
  'movie_id': 144185,
  'movie_isshowtime': 1,
  'movie_label': 'suicide_squad',
  'nationality': '5002',
  'press_rating': 2,
  'releasedate': '2016-08-03',
  'site_route': 'moviepage_videos_trailer',
  'site_section': 'movie',
  'user_activity': 'videowatch',
  'user_rating': 3.4,
  'video_id': 19561982,
  'video_label': 'suicide_squad_bande_annonce_finale_vo',
  'video_type_id': 31003,
  'video_type_label': 'trailer'}]

您也可以使用正则表达式,但在这种情况下,使用 str.find 获取数据的末尾就足够了。

关于javascript - 使用 python 抓取时访问数据层(JS 变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39142846/

相关文章:

javascript - 使用 backbone.js 构建监控前端

python - 为什么不能 unpickled 这个 set 子类的实例?

2019 年的 Python 2/3 异步

windows - 从 ubuntu 创建快捷窗口文件

python - tensorflow 将 tf.int32 转换为 tf.string 在适合 Google 云 ml-engine 的版本中

javascript - D3.js 折线图工具提示问题

javascript - 仅在淡出后加载内容

javascript - 防止点击 React-Fiber Three.js 中的对象

python - 在 Python 中将 SHA256 哈希字符串转换为 SHA256 哈希对象

javascript - 递归启用/禁用 div 中按钮的方法?