【问题标题】:How do you find inside a div element with bs4?如何使用 bs4 在 div 元素中找到?
【发布时间】:2019-09-29 09:38:48
【问题描述】:

我正在制作一个 python 脚本来提供网站 scratch.mit.edu 上的前 5 个特色项目。我正在使用请求来获取数据。具有这些项目标题的元素位于 div 标签中,但是当我使用 bs4 时,它不显示 div 标签的子代或后代。如何查看标签内部?

我尝试过 find_all()、find()、.descendants 和 .children。

soup.find("div").children

我期望

的输出

【问题讨论】:

标签: python html web-scraping beautifulsoup


【解决方案1】:

API

使用页面用来更新内容和解析json响应的api

https://api.scratch.mit.edu/proxy/featured

import requests
import pandas as pd

r = requests.get('https://api.scratch.mit.edu/proxy/featured').json()
project_info  = [(item['title'], 'https://scratch.mit.edu/projects/' + str(item['id'])) for item in r['community_featured_projects'][:6]]
df = pd.DataFrame(project_info , columns = ['Title', 'Link'])
print(df.head())

或者,次优选择,因为内容是动态呈现的,您可以使用像 selenium 这样的方法:

限制在第一个“框”,然后选择thumbnail-title 类的子a 标记并索引到前5/ 或df.head() 列表中

.box:nth-of-type(1) .thumbnail-title > a

py(如@P.hunter 所述——你可以无头运行)

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import pandas as pd

options = Options()  
options.add_argument("--headless") 

d = webdriver.Chrome(options = options)
d.get('https://scratch.mit.edu/')
project_info = [(item.get_attribute('title') ,item.get_attribute('href') ) for item in  WebDriverWait(d,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".box:nth-of-type(1) .thumbnail-title > a")))]
df = pd.DataFrame(project_info , columns = ['Title', 'Link'])
d.quit()
print(df)

【讨论】:

  • 无头操作会更好,对吧? options.add_argument('--headless') options.add_argument('--disable-gpu') # Last I checked this was necessary. driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)
  • @P.hunter options.add_argument('--disable-gpu') 有什么好处?消除不必要的开销?
  • 它与windows的一些问题有关,当时是一个临时标志,将在以后的版本中删除,但是我做了一些研究,发现在新版本中--disable-gpu是现在不需要,你可以做options = Options() options.headless = True driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe') 请更新答案:)
猜你喜欢
  • 2017-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
相关资源
最近更新 更多