采用BeautifulSoup库无法解析到网址信息,求解决方法

网址源码如下:

<span class="company-page-item-right cmpweb">
 <a target="_blank" href="http://www.gmgitc.com">www.gmgitc.com</a>
</span>

通过BS解析后,无法获取a标签内容

import requests
from bs4 import BeautifulSoup

intro_url = 'https://xinsanban.eastmoney.com/F10/CompanyInfo/Introduction/831039.html'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\
            /537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'}
resp = requests.get(intro_url, headers=headers, timeout=1)
print(bs)
___________________________________________________________________________________________________
<li class="even">
<span class="company-page-item-left ">公司网址</span>
<span class="company-page-item-right cmpweb"/>
</li>



因为这个网页中的公司网址是通过js代码来动态更新的。
requests只能获取网页的静态源代码,动态更新的内容取不到。
对于动态更新的内容要用selenium 来爬取。

在页面上点击右键,右键菜单中选 "查看网页源代码"。

img


这样看到的才是网页的静态源代码。

img

可以看到这个网页的静态源代码中没有你需要的<a target="_blank" href="http://www.gmgitc.com">www.gmgitc.com</a>
说明该页面的内容是动态更新的,要用selenium 来爬取,比如:.

from selenium import webdriver
import time
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
intro_url = 'https://xinsanban.eastmoney.com/F10/CompanyInfo/Introduction/831039.html'
driver.get(intro_url)
time.sleep(3)
html = driver.page_source
soup=BeautifulSoup(html,'lxml')
req=soup.select('span.company-page-item-right.cmpweb')[0]
print(req)

img

静态页面数据用以下语句就可以了,公司网址信息动态加载则需要用selenium

soup=BeautifulSoup(resp.text,'lxml')
req=[x.text.strip()+':'+y.text.strip() for x,y in zip(soup.select('li.even span.company-page-item-left'),soup.select('li.even span.company-page-item-right'))]
print(req)
req1=[x.text.strip() for x in soup.select('li.even span.company-page-item-left ~span')]#~span 换成 ~a获取邮箱地址。
print(req1)

如对你有帮助,请采纳。点击我回答右上角【采纳】按钮。