gpt4 book ai didi

python - 简短而简单 - soup.find_all 不返回多个标签元素

转载 作者:太空宇宙 更新时间:2023-11-03 14:28:03 24 4
gpt4 key购买 nike

我需要抓取所有具有“result-title”类的“a”标签,以及具有“results-price”和“results-hood”类的所有“span”标签。然后,将输出写入跨多列的 .csv 文件。当前代码不会向 csv 文件打印任何内容。这可能是糟糕的语法,但我真的看不出我错过了什么。谢谢。

f = csv.writer(open(r"C:\Users\Sean\Desktop\Portfolio\Python - Web Scraper\RE Competitor Analysis.csv", "wb"))

def scrape_links(start_url):
for i in range(0, 2500, 120):
source = urllib.request.urlopen(start_url.format(i)).read()
soup = BeautifulSoup(source, 'lxml')
for a in soup.find_all("a", "span", {"class" : ["result-title hdrlnk", "result-price", "result-hood"]}):
f.writerow([a['href']], span['results-title hdrlnk'].getText(), span['results-price'].getText(), span['results-hood'].getText() )
if i < 2500:
sleep(randint(30,120))
print(i)


scrape_links('my_url')

最佳答案

如果您想通过一次调用 find_all 查找多个标签,您应该将它们传递到一个列表中。例如:

soup.find_all(["a", "span"])

如果无法访问您正在抓取的页面,就很难为您提供完整的解决方案,但我建议一次提取一个变量并打印它以帮助您调试。例如:

a = soup.find('a', class_ = 'result-title')
a_link = a['href']
a_text = a.text

spans = soup.find_all('span', class_ = ['results-price', 'result-hood'])

row = [a_link, a_text] + [s.text for s in spans]
print(row) # verify we are getting the results we expect

f.writerow(row)

关于python - 简短而简单 - soup.find_all 不返回多个标签元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47482206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com