Python - 合并两个for循环为数组

2024-09-30 20:31:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,正在学习,尝试结合多个教程中的知识来解决我的问题

基本上,我期待着刮下面的网站拉出来的所有属性和相应的网页链接到一个数组

网站:“https://www.accommodationforstudents.com/search-results?location=London&area=&beds=0&searchType=halls&price=undefined&limit=99

问题是,当我运行代码时,它会正确地遍历每个属性的链接,但属性的名称不会。如果有任何帮助,我将不胜感激

敬礼

import urllib.request
import requests
from bs4 import BeautifulSoup

url = "https://www.accommodationforstudents.com/search-results?location=London&area=&beds=0&searchType=halls&price=undefined&limit=99"

response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

page = soup.findAll('a', attrs={'class': "student-halls-card__link"})
property = soup.findAll('strong', attrs={'class': "student-halls-card__title"})

sites = []


for link in page:
    link.find('href', attrs={'class': "student-halls-card__link"})

    for name in property:
        name.find('href', attrs={'class': 'student-halls-card__title'})

    sites.append(name.text + " - " + "https://www.accommodationforstudents.com" + link.get('href'))

print(sites)

结果缩短。。 'Felda House-https://www.accommodationforstudents.com/student-hall/407'、'Felda House-https://www.accommodationforstudents.com/student-hall/1672'、'Felda House-https://www.accommodationforstudents.com/student-hall/3260'、……………………]


Tags: httpsimportcom属性wwwlinkcardstudent