4 回答

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
在我看來,您的第二個(gè) for 循環(huán)for p_tag in item.find_all('p'):
不在第一個(gè) for 循環(huán)的范圍內(nèi),該循環(huán)遍歷項(xiàng)目...添加到第一個(gè)循環(huán)中可能有 0 個(gè)項(xiàng)目的事實(shí),您得到一個(gè)無。
只需將 for 循環(huán)及其內(nèi)容放在迭代 pipeline_items 中的項(xiàng)目的 for 循環(huán)中。

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
問題是
pipeline_items = soup.find_all('div', attrs={'class': 'pipline-item'})
返回一個(gè)空列表。這樣做的結(jié)果是:
for item in pipeline_items:
從來沒有真正發(fā)生過。因此,item
永遠(yuǎn)不會(huì)定義 的值。
我不確定你到底想做什么。但我看到兩個(gè)解決方案:
縮進(jìn)
for p_tag in item.find_all('p'):
以便為每個(gè)項(xiàng)目執(zhí)行它。這樣,如果沒有項(xiàng)目,它就不會(huì)被調(diào)用(我想這就是你原本打算做的?)在循環(huán)前加if語句判斷是否
item
存在,不存在則跳過循環(huán)。哪個(gè)最接近復(fù)制您的代碼當(dāng)前正在執(zhí)行的操作,但我認(rèn)為這不是您希望它執(zhí)行的操作。

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊
第 17 行及以下需要在 for 循環(huán)內(nèi)才能看到“item”。
for item in pipeline_items:
# title, image url, listing url
listing_title = item.a['title']
listing_url = item.a['href']
listing_image_url = item.a.img['src']
for p_tag in item.find_all('p'): <------------Indent this for loop to be inside the previous for loop.
if not p_tag.h2:
if p_tag.text == 'Location:':

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
任務(wù)完成感謝這里的每一個(gè)人,干杯!我遺漏了一些東西。1 確定縮進(jìn)。2 我錯(cuò)過了第一小節(jié)的跨度——如果 p_tag.span.text == 'Location:': 3 我錯(cuò)過了一個(gè)包 openpyxl,它在底部被調(diào)用以寫入 excel。
下面 100% 的工作代碼,我承諾會(huì)變得更好并在我可以的時(shí)候提供幫助 :)
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'https://dc.urbanturf.com/pipeline'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
pipeline_items = soup.find_all('div', attrs={'class': 'pipeline-item'})
rows = []
columns = ['listing title', 'listing url', 'listing image url', 'location', 'Project type', 'Status', 'Size']
for item in pipeline_items:
# title, image url, listing url
listing_title = item.a['title']
listing_url = item.a['href']
listing_image_url = item.a.img['src']
for p_tag in item.find_all('p'):
if not p_tag.h2:
if p_tag.span.text == 'Location:':
p_tag.span.extract()
property_location = p_tag.text.strip()
elif p_tag.span.text == 'Project type:':
p_tag.span.extract()
property_type = p_tag.text.strip()
elif p_tag.span.text == 'Status:':
p_tag.span.extract()
property_status = p_tag.text.strip()
elif p_tag.span.text == 'Size:':
p_tag.span.extract()
property_size = p_tag.text.strip()
row = [listing_title, listing_url, listing_image_url, property_location, property_type, property_status, property_size]
rows.append(row)
df = pd.DataFrame(rows, columns=columns)
df.to_excel('DC Pipeline Properties.xlsx', index=False)
print('File Saved')
添加回答
舉報(bào)