我的目标是在<div class="items-box-body">中获取商品名称(棉质衬衫)和价格(人民币3,600元)。
<div class="items-box-body">
<h3 class="items-box-name font-2">cotton shirt</h3>
<div class="items-box-num">
<div class="items-box-price font-5">¥3,600</div>
</div>
</div>我使用了下面的代码,但无法访问任何div。当我测试soup.find_all()时,我看不到body之间的任何内容。
from bs4 import BeautifulSoup
from selenium import webdriver
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path=r'C:\Users\...', chrome_options=options)
soup = BeautifulSoup(driver.page_source, "html.parser")
site_url = 'https://www.mercari.com/jp/search/?sort_order=&keyword=&category_root=1&category_child=11&category_grand_child%5B122%5D=1&brand_name=&brand_id=&size_group=&price_min=&price_max=&item_condition_id%5B1%5D=1&shipping_payer_id%5B2%5D=1&status_on_sale=1'
response = driver.get(site_url)
time.sleep(5)
print(soup.html.unwrap())
>> <html></html>
test = soup.find_all()
print('1',test)
>> [<head></head>, <body></body>]
body = soup.body()
print('2',body)
>> 2 []
for item in soup.select('div[class*="default-container "]'):
print('3', item)
>>
for item in soup.select('div[class*="items-box-body"]'):
print('4', item)
>>我做错什么了?
发布于 2020-05-06 08:55:36
以获取产品名称和价格。诱导WebDriverWait()并等待visibility_of_all_elements_located()加载元素,然后使用page_source进行进一步的处理。
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
from selenium import webdriver
site_url = 'https://www.mercari.com/jp/search/?sort_order=&keyword=&category_root=1&category_child=11&category_grand_child%5B122%5D=1&brand_name=&brand_id=&size_group=&price_min=&price_max=&item_condition_id%5B1%5D=1&shipping_payer_id%5B2%5D=1&status_on_sale=1'
driver.get(site_url)
WebDriverWait(driver,10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,".items-box")))
html=driver.page_source
soup=BeautifulSoup(html,'html.parser')
for item in soup.select('.items-box'):
print(item.find_next('h3',class_='items-box-name font-2').text.strip())
print(item.find_next('div', class_='items-box-price font-5').text) 您可以在不使用selenium的情况下使用python请求模块来完成这个任务。
from bs4 import BeautifulSoup
import requests
headers = {'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
res=requests.get("https://www.mercari.com/jp/search/?sort_order=&keyword=&category_root=1&category_child=11&category_grand_child%5B122%5D=1&brand_name=&brand_id=&size_group=&price_min=&price_max=&item_condition_id%5B1%5D=1&shipping_payer_id%5B2%5D=1&status_on_sale=1",headers=headers).text
soup=BeautifulSoup(res,'html.parser')
for item in soup.select('.items-box'):
print(item.find_next('h3',class_='items-box-name font-2').text.strip())
print(item.find_next('div', class_='items-box-price font-5').text)https://stackoverflow.com/questions/61630593
复制相似问题