起风了番茄 发表于 2022-3-24 23:01:05

小甲鱼爬豆瓣TOP250有个代码看不懂

import requests
import bs4
import re

def open_url(url):
    #使用代理
    # proxies = {'https':'223.243.174.152:9999','https':'223.214.205.179:9999'}
    headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.46'}
    res = requests.get(url,headers=headers)
    return res

def find_movies(res):
    #炖汤
    soup = bs4.BeautifulSoup(res.text,'html.parser')
    #电影名
    movies = []
    targets = soup.find_all('div',class_ = 'hd')
    for each in targets:
      movies.append(each.a.span.text)

    #评分
    ranks = []
    targets = soup.find_all('span',class_='rating_num')
    for each in targets:
      ranks.append('评分%s'%each.text)
    #资料
    messages = []
    targets = soup.find_all('div',class_='bd')
    for each in targets:
      try:
            messages.append(each.p.text.split('\n').strip() + each.p.text.split('\n').strip())
      except:
            continue

    result = []
    length = len(movies)
    for i in range(length):
      result.append(movies + ranks + messages +'\n')
    return result

#找出一共有多少个页面
def find_depth(res):
    soup = bs4.BeautifulSoup(res.text,'html.parser')
    depth = soup.find('span',class_= 'next').previous_sibling.previous_sibling.text #这一行什么意思呀?
    return int(depth)

def main():
    host = 'https://movie.douban.com/top250'
    res = open_url(host)
    depth = find_depth(res)

    result = []
    for i in range(depth):
      url = host + '/?start='+str(25*i)
      res =open_url(url)
      result.extend(find_movies(res))

    with open('豆瓣TOP250.txt','w',encoding='utf-8') as f:
      for each in result:
            f.write(each)

if __name__ == '__main__':
    main()

起风了番茄 发表于 2022-3-24 23:02:57

我知道previous_sibling是找之前的同级标签,可是我查看了html代码还是只有个大体的猜测,需要大佬们的指导下.

isdkz 发表于 2022-3-24 23:05:27

https://blog.csdn.net/Winterto1990/article/details/47794941

起风了番茄 发表于 2022-3-25 16:34:34

isdkz 发表于 2022-3-24 23:05
https://blog.csdn.net/Winterto1990/article/details/47794941

可是我看使用两次previous_sibling找到的不应该是9号标签吗?

cxslovefishc 发表于 2022-3-26 21:58:43

就是span节点的上一个兄弟节点的上一个兄弟节点,这么说你看你有点乱,我举一个例子吧
In : text = "<div><a>text0</a><b>text1</b><c>text2</c></div>"
In : soup = bs4.BeautifulSoup(text, "html.parser")
In : soup.find("c").previous_sibling.previous_sibling.text
Out: 'text0'
c的上上个兄弟节点就是a,所以拿到的文本是text0

C丁洞杀O 发表于 2022-3-27 08:34:15

啥子东东啊??
页: [1]
查看完整版本: 小甲鱼爬豆瓣TOP250有个代码看不懂