这是我的代码:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import pandas as pd
driver = webdriver.Chrome(service=Service(executable_path=ChromeDriverManager().install()))
driver.maximize_window()
driver.get('https://quotes.toscrape.com/')
df = pd.DataFrame(
{
'Quote': [''],
'Author': [''],
'Tags': [''],
}
)
quotes = driver.find_elements(By.CSS_SELECTOR, '.quote')
for quote in quotes:
text = quote.find_element(By.CSS_SELECTOR, '.text')
author = quote.find_element(By.CSS_SELECTOR, '.author')
tags = quote.find_elements(By.CSS_SELECTOR, '.tag')
for tag in tags:
quote_tag = tag
df = df.append(
{
'Quote': text.text,
'Author': author.text,
'Tags': quote_tag.text,
},
ignore_index = True
)
df.to_csv('C:/Users/Jay/Downloads/Python/!Learn/practice/scraping/selenium/quotes.csv', index=False)
我应该得到这个结果:
相反,我得到了这个:
我只得到 Tags
中的最后一项列而不是所有四个项目。
如果我运行:
quotes = driver.find_elements(By.CSS_SELECTOR, '.quote')
for quote in quotes:
tags = quote.find_elements(By.CSS_SELECTOR, '.tag')
for tag in tags:
quote_tag = tag
print(quote_tag.text)
我得到:
change
deep-thoughts
thinking
world
etc
所以这段代码可以工作。
为什么不是 Tags
列是否已正确填充?
最佳答案
对于您的循环,请使用以下代码:
quote_tags = []
for tag in tags:
quote_tags.append(tag.text)
df = df.append(
{
'Quote': text.text,
'Author': author.text,
'Tags': ' '.join(quote_tags),
},
ignore_index = True
)
如果您注意到,唯一添加的标签 (world
) 恰好是最后一个标签......这不是巧合。这是因为您循环遍历标签,并且对于每个标签,您将该标签分配给 quote_tag
变量,但您没有对其执行任何操作,因此下一次循环迭代只会覆盖由上一次迭代。最后,当循环结束时,quote_tag
具有最后一个标记的值。
关于python - 为什么我在 pandas 列中只得到一项(而不是多项)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70028861/