【问题标题】:How to find Specific item in <script> using BS4 web scraping如何使用 BS4 网页抓取在 <script> 中查找特定项目
【发布时间】:2021-05-01 01:39:12
【问题描述】:

我想在下面的脚本中获取 id。阿尔萨

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
driver = webdriver.Chrome(options=options)

url = "https://www.beko.com.tr/cift-kapili-buzdolabi/b1-8459-smn-buzdolabi"
print(url)
driver.get(url)
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')


id_all = soup.find_all('script')

print(id_all)

driver.close()

---------------output is more complex but I just want to get below 'id': '7291920212'------


 </script>, <script>
        dataLayer.push ({

            'ecommerce' : {

              'detail': {
                'actionField': {'list': ''},
                'products' : [
                  {
                    'name': 'B1 8459 SMN',
                    'id': '7291920212',
                    'brand': 'Beko',
                    'variant': 'Null',
                    'category': ''

                  }
                ]
              },

【问题讨论】:

标签: javascript python python-3.x web-scraping beautifulsoup


【解决方案1】:

尝试使用regex

例如:

import re

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
driver = webdriver.Chrome(options=options)

url = "https://www.beko.com.tr/cift-kapili-buzdolabi/b1-8459-smn-buzdolabi"
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
print(re.search(r'content_ids:\["(\d+)"\]', str(soup.find_all('script')), re.S).group(1))

driver.close()

输出:

7291920212

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多