使用beauthoulsoup4和Python抓取有序列表

2024-09-27 17:50:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python/BS4和数据抓取还比较陌生,所以我觉得这是一个简单的问题,但是我很难在网上找到任何资源。在

我的目标是使用this site生成随机地址,并使用BS4将它们刮取。在

我目前的代码如下:

site = 'https://www.randomlists.com/random-addresses?qty=10'

res = requests.get(site)
soup = bs4.BeautifulSoup(res.text, 'html.parser')

bigdata = soup.find('ol',{'class':'rand_large'})
print(bigdata)

返回“无”

我看到我想要的数据在一个‘ol’内,我理解为一个有序列表。我在过去做了一些基本的抓取,我很困惑为什么上面的代码找不到“rand_large”。在

有什么建议吗?在

小编辑/添加:使用

^{pr2}$

退货:

^{3}$

我不明白多余的“东西”是从哪里来的。在


Tags: 数据代码目标地址siteres资源this
1条回答
网友
1楼 · 发布于 2024-09-27 17:50:35
In[2]: from bs4 import BeautifulSoup
  ...: from selenium import webdriver
  ...: 
  ...: url = 'https://www.randomlists.com/random-addresses'
  ...: 
  ...: chrome_options = webdriver.ChromeOptions()
  ...: chrome_options.add_argument(' headless')
  ...: driver = webdriver.Chrome(options=chrome_options)
  ...: 
  ...: driver.get('{}?qty={}'.format(url, 1346))
  ...: html = driver.page_source
  ...: driver.quit()
  ...: 
  ...: soup = BeautifulSoup(html, 'lxml')
  ...: result = []
  ...: for li in soup.find('ol', class_='rand_large').find_all('li'):
  ...:     result.append(list(li.stripped_strings))
  ...: 
In[3]: len(result)
Out[3]: 1346
In[4]: result[:10]
Out[4]: 
[['2 Tanglewood Dr.', 'Ringgold, GA 30736'],
 ['7538 South Windfall Avenue', 'Marysville, OH 43040'],
 ['944 Harvey Street', 'Stevens Point, WI 54481'],
 ['804 Smith St.', 'Des Plaines, IL 60016'],
 ['78 Bohemia Road', 'Williamstown, NJ 08094'],
 ['7509 San Juan Dr.', 'Cranston, RI 02920'],
 ['8003 6th Street', 'Inman, SC 29349'],
 ['118 Roosevelt Dr.', 'Fort Worth, TX 76110'],
 ['242 Young Lane', 'Mcdonough, GA 30252'],
 ['3 Marsh St.', 'Bay Shore, NY 11706']]

相关问题 更多 >

    热门问题