2

问题:

有一个网站https://au.pcpartpicker.com/products/cpu/overall-list/#page=1<li>下有一个列表,列表中的<ul>每个项目都包含一个<div>带有类标题的类中还有 2 个<div>元素第一个有一些文本示例3.4 GHz 6-Core (Pinnacle Ridge)我想删除所有不在括号中的文本以获得Pinnacle Ridge删除列表后,我想通过更改#page=进入下一页。

代码:

我不太确定只有片段,但这里是:

从 requests_html 导入 HTMLSession 会话 = HTMLSession()

r = session.get('https://au.pcpartpicker.com/product/cpu/overall-list/#page=' + page)

table = r.html.find('.ul')

//not sure find each <li> get first <div>

junk, name = div.split('(')

name.replace("(", "")

name.replace(")", "")

预期结果:

我想遍历每个页面,直到没有人找到每个列表并获取不需要保存的名称,因为我有代码在创建它时保存它。

如果您需要更多信息,请告诉我

谢谢

4

1 回答 1

1

该站点是动态的,因此,您必须使用它selenium来产生所需的结果:

from bs4 import BeautifulSoup as soup
from selenium import webdriver
import time, re
d = webdriver.Chrome('/path/to/chromdriver')
d.get('https://au.pcpartpicker.com/products/cpu/overall-list/#page=1')
def cpus(_source):
  result = soup(_source, 'html.parser').find('ul', {'id':'category_content'}).find_all('li')
  _titles = list(filter(None, [(lambda x:'' if x is None else x.text)(i.find('div', {'class':'title'})) for i in result]))
  data = [list(filter(None, [re.findall('(?<=\().*?(?=\))', c.text) for c in i.find_all('div')])) for i in result]
  return _titles, [a for *_, [a] in filter(None, data)]


_titles, _cpus = cpus(d.page_source))
conn.executemany("INSERT INTO cpu (name, family) VALUES (?, ?)", list(zip(_titles, _cpus)))
_last_page = soup(d.page_source, 'html.parser').find_all('a', {'href':re.compile('#page\=\d+')})[-1].text
for i in range(2, int(_last_page)+1):
   d.get(f'https://au.pcpartpicker.com/products/cpu/overall-list/#page={i}') 
   time.sleep(3)
   _titles, _cpus = cpus(d.page_source))
   conn.executemany("INSERT INTO cpu (name, family) VALUES (?, ?)", list(zip(_titles, _cpus)))
于 2018-12-29T00:27:16.987 回答