鱼C论坛

 找回密码
 立即注册
查看: 1769|回复: 4

[已解决]如何在url标签相同的情况下,爬取下一个数据呢?

[复制链接]
发表于 2023-6-1 14:27:14 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
如题,网页源代码如下:
企业微信截图_16856007017789.png

我的代码
def find_company(res):
    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    # 公司名
    company = []
    targets = soup.find_all("span", class_="ttspan")
    for each in targets:
        company.append(each.text)

    # 主营产品
    products = []
    targets = soup.find_all("span", class_="clr")
    for each in targets:
        products.append(each.text)

    # 经营模式
    busmdl = []
    targets = soup.find_all("span", class_="clr")
    for each in targets:
        busmdl.append(each.text)

    # 成立时间
    estabtime = []
    targets = soup.find_all("span", class_="clr")
    for each in targets:
        estabtime.append(each.text)

    # 公司地址
    address = []
    targets = soup.find_all("span", class_="clr")
    for each in targets:
        address.append(each.text)

    result = []
    length = len(company)
    for i in range(length):
        result.append([company[i], products[i], busmdl[i], estabtime[i], address[i]])

    return result

这样下来每个信息都会被同样的循环4遍导致输出内容一样,如何使用bs4找到特定的数据呢?
最佳答案
2023-6-1 14:31:37
本帖最后由 歌者文明清理员 于 2023-6-1 14:53 编辑

爬取一次不就行了吗
def find_company(res):
    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    company = [each.text for each in soup.find_all("span", class_="ttspan")]
    ress = [each.text for each in soup.find_all("span", class_="clr")]
    products = ress[::4]
    busmdl = ress[1::4]
    estabtime = ress[2::4]
    address = ress[3::4]

    result = [list(i) for i in zip(company, products, busmdl, estabtime, address)]

    return result
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-6-1 14:31:37 | 显示全部楼层    本楼为最佳答案   
本帖最后由 歌者文明清理员 于 2023-6-1 14:53 编辑

爬取一次不就行了吗
def find_company(res):
    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    company = [each.text for each in soup.find_all("span", class_="ttspan")]
    ress = [each.text for each in soup.find_all("span", class_="clr")]
    products = ress[::4]
    busmdl = ress[1::4]
    estabtime = ress[2::4]
    address = ress[3::4]

    result = [list(i) for i in zip(company, products, busmdl, estabtime, address)]

    return result

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +3 收起 理由
Banky + 5 + 5 + 3

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2023-6-1 14:46:50 | 显示全部楼层

虽然有bug,但我看懂方法了,感谢老哥带我走出误区
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-6-1 14:48:11 | 显示全部楼层
Banky 发表于 2023-6-1 14:46
虽然有bug,但我看懂方法了,感谢老哥带我走出误区

你不给链接我不知道我的代码写的对不对
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-6-1 14:50:17 | 显示全部楼层
Banky 发表于 2023-6-1 14:46
虽然有bug,但我看懂方法了,感谢老哥带我走出误区

我知道代码错在哪里了,改了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-22 23:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表