pandas 将Href链接附加到列表,但列表仅显示其中的一部分

nkcskrwz  于 2023-03-28  发布在  其他
关注(0)|答案(1)|浏览(87)

我从下面的这个网站中抓取链接,有超过4000个值,但我设法只获取了78个列表。当我运行第一个代码时,有一个很好的输出,说它都被附加到列表中

for i in range(1, 206):
   url = f"https://www.oglasnik.hr/prodaja-automobila?page%7Bi%7D=" ##added loop through pages function, turned string into variable
   page = requests.get(url)
   soup = BeautifulSoup(page.content, 'html.parser')
   a = soup.find_all('a', href=re.compile('https://www.oglasnik.hr/prodaja-automobila/'))
  list1=\[\]
  for ele in a:
     link = ele.get('href')
     list1.append(link)
     print(f"Appended link: {link}")

我把所有的链接都刮了出来,当我调出列表时,得到了一个大约4000个链接的小输出,使用:print(list1)
78个链接
我也试过把它做成一个csv文件,我得到了78行。

df = pd.DataFrame(list(zip(list1)), columns = \['Link'\]) #adding the list to csv file

try:
df.to_csv('links.csv', index=False)
print("Links saved to CSV file successfully!") #adding expection to recognize error
except Exception as e:
print(f"Error saving links to CSV file: {e}")
blmhpbnm

blmhpbnm1#

要将所有链接放入DataFrame,您可以使用下一个示例:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'https://www.oglasnik.hr/prodaja-automobila?page='

all_links = []
for page in range(1, 207):
    print(page)
    soup = BeautifulSoup(requests.get(f'{url}{page}').content, 'html.parser')
    all_links.extend(a['href'] for a in soup.select('a[href*="/prodaja-automobila/"]'))

df = pd.DataFrame({'Link': all_links})
print(df.head())
print(len(df))
df.to_csv('data.csv', index=False)

图纸:

...

204
205
206

                                                                                                                          Link
0                https://www.oglasnik.hr/prodaja-automobila/opel-insignia-grand-sport-1-6-cdti-ecotec-innovation-oglas-5143006
1                   https://www.oglasnik.hr/prodaja-automobila/isporuka-odmah-nissan-micra-1-0-ig-t-n-sport-novo-oglas-5147151
2               https://www.oglasnik.hr/prodaja-automobila/audi-a6-3-0-tdi-quattro-272ks-s-line-webasto-mmi-plus-oglas-5174610
3  https://www.oglasnik.hr/prodaja-automobila/vw-passat-variant-2-0-tdi-bmt-dsg-automatik-pdv-facelift-garancija-oglas-5175629
4                                            https://www.oglasnik.hr/prodaja-automobila/renault-megane-grandtour-oglas-3518246

4157

并保存data.csv,其中包含4157个链接(Libre Office截图):

相关问题