python - 抓取网页 <ul> <li>(Python)

标签 python html python-3.x beautifulsoup python-requests-html

问题:

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

代码:

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

从 requests_html 导入 HTMLSession session = 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(")", "")

预期结果:

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

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

谢谢

最佳答案

该站点是动态的,因此,您必须使用 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)))

关于python - 抓取网页 <ul> <li>(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53965541/

相关文章:

python - 在版本 56.0.2924.87 中,Selenium 在 Chrome 中设置窗口大小失败

python - 快速 Numpy 循环

jquery - 如何使用来自 json/jquery 的数据创建表?

php - 有没有办法使 GET/POST 数据只能使用一次并在刷新时清除?

python - 为什么 justify 和anchor 对于 Python Tkinter 的 Label 不起作用

python - Tensorflow GPU 利用率低于 10%

python - 给定两个元组列表找到它们之间最近的元组(dist

JavaScript/jQuery : Validate Checkbox & Dropdown Pairing

Python追加到数组并为它循环

python - 尝试在 mac OS 中运行此命令 "pipenv install requests "时出错