简单爬虫尝试

简单爬虫

研究一下怎样让AI理解我想爬取的内容并迅速给出我准确的代码

  • 目标网页

    https://www.greataiprompts.com/chat-gpt/best-chat-gpt-prompts/

  • prompt:
    爬取https://www.greataiprompts.com/chat-gpt/best-chat-gpt-prompts/
    里面的所有

    里面的内容,写入字典, 表头是key,表里面其他内容作为value

    这个prompt没达到效果,cursor给我的代码它只爬取了第一个表格

  • prompt:
    爬取https://www.greataiprompts.com/chat-gpt/best-chat-gpt-prompts/
    里面的所有

  • 里面的内容,页面中有好几个表格,
    写入字典, 每个key对应一个表头,表里面其他内容作为value

    这个prompt实现了效果,里面的很多注释是我引导copilot添加的

    import requests
    from bs4 import BeautifulSoup
    
    url = 'https://www.greataiprompts.com/chat-gpt/best-chat-gpt-prompts/'
    response = requests.get(url)
    # soup是BeautifulSoup对象
    soup = BeautifulSoup(response.text, 'html.parser')
    # soup.find_all('table')返回的是一个列表
    tables = soup.find_all('table')
    
    data = {}
    
    # 遍历列表中的每个table
    for table in tables:
        # headers是一个列表,里面的元素是th标签中的文本,th是一个BeautifulSoup对象,th的全称是table header
        headers = []
        for th in table.find_all('th'):
            headers.append(th.text.strip())
        rows = []
        # 遍历tr标签 tr是一个BeautifulSoup对象,tr的全称是table row
        for tr in table.find_all('tr'):
            row = []
            # td是一个BeautifulSoup对象,td的全称是table data
            # 这个循环的意思是遍历tr标签中的所有td标签,然后把td标签中的文本放到row列表中
            for td in tr.find_all('td'):
                # strip()方法是去掉字符串两边的空格
                row.append(td.text.strip())
            # 如果row列表不为空,就把row列表放到rows列表中
            if row:
                rows.append(row)
        # 把headers列表中的每个元素作为key,把rows列表中的每个元素作为value,放到data字典中
        for i in range(len(headers)):
            # [row[i] for row in rows]是一个列表推导式,意思是把rows列表中的每个元素的第i个元素放到一个列表中
            data[headers[i]] = [row[i] for row in rows]
    
    print(data)
    
  • 下一步存入json

    有点小瑕疵,每个table都是有序号的,但是不知道为啥只识别了几个 S.No. 作为表头,然后其他的 S.No. 没有放入data字典

    那就手动删下吧

    存入json的代码

    
    with open('data3.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
    
    
  • 你可能感兴趣的:(#,python爬虫,爬虫,python)