我正在尝试使用 Python 中的 Beautifulsoup 从华尔街日报中抓取文章。但是,我正在运行的代码执行没有任何错误(退出代码 0)但没有结果。我不明白发生了什么?为什么这段代码没有给出预期的结果。
我什至支付了订阅费。
我知道有些地方不对,但我找不到问题所在。
import time
import requests
from bs4 import BeautifulSoup
url = 'https://www.wsj.com/search/term.html?KEYWORDS=cybersecurity&min-date=2018/04/01&max-date=2019/03/31' \
'&isAdvanced=true&daysback=90d&andor=AND&sort=date-desc&source=wsjarticle,wsjpro&page={}'
pages = 32
for page in range(1, pages+1):
res = requests.get(url.format(page))
soup = BeautifulSoup(res.text,"lxml")
for item in soup.select(".items.hedSumm li > a"):
resp = requests.get(item.get("href"))
_href = item.get("href")
try:
resp = requests.get(_href)
except Exception as e:
try:
resp = requests.get("https://www.wsj.com" + _href)
except Exception as e:
continue
sauce = BeautifulSoup(resp.text,"lxml")
date = sauce.select("time.timestamp.article__timestamp.flexbox__flex--1")
date = date[0].text
tag = sauce.select("li.article-breadCrumb span").text …Run Code Online (Sandbox Code Playgroud) 对不起,如果标题令人困惑,但我已经研究了两个小时,并且不知道我应该如何问这个问题,所以任何人都可以随意编辑这篇文章。
我有这个字符串变量,我使用网络抓取创建了它,它使用特殊字符,看起来像“\ud83d\ude00\u0107\u00e7\n hello”,打印时没有引号。问题是我希望它打印实际的特殊字符,但我不确定应该使用哪种编码方法。如果我复制并粘贴确切的字符串并打印它,它工作正常,但作为我创建的变量,它不显示特殊字符,只显示文本。
我曾尝试使用 json.load、unicode-escape、UTF-8 和其他一些方法将其转换为字符串,但老实说我不确定我应该使用什么方法
page = requests.get('https://www.example.com')
soup = str(BeautifulSoup(page.text, 'html.parser')).splitlines()
for line in soup:
if 'hello' in line:
print(line) #produces literal text of \ud83d\ude00\u0107\u00e7 \n hello
print('\ud83d\ude00\u0107\u00e7 \n hello') #produces wanted result
Run Code Online (Sandbox Code Playgroud)
我希望结果看起来像这样:
?C
你好
所以我使用库 BeautifulSoup 从表中提取数据,代码如下:
if soup.find("table", {"class":"a-keyvalue prodDetTable"}) is not None:
table = parse_table(soup.find("table", {"class":"a-keyvalue prodDetTable"}))
df = pd.DataFrame(table)
Run Code Online (Sandbox Code Playgroud)
所以这行得通,我得到了表 nad 将其解析为数据帧,但是我正在尝试使用 selenium 在不同的网站上做类似的事情,这是我目前的代码:
driver = webdriver.Chrome()
i = "DCD710S2"
base_url = str("https://www.lowes.com/search?searchTerm=" + str(i))
driver.get(base_url)
table = driver.find_element_by_xpath("//*[@id='collapseSpecs']/div/div/div[1]/table/tbody")
Run Code Online (Sandbox Code Playgroud)
所以我进入了表格,我尝试使用 getAttribute(innerHTML) 和其他一些 getAttribute 元素,但我无法将表格按原样放入 Pandas。关于如何用硒处理的任何建议?
selenium beautifulsoup python-3.x pandas selenium-chromedriver
我正在尝试通过 BeautifulSoup 用 lxml 解析一个很长的 html 文件。我知道 html 文件的字符编码是,UTF-8 with BOM但是每当我尝试运行时,contents = f.read()我都会收到以下错误:'charmap' codec can't decode byte 0x8d in position 33222: character maps to <undefined>
这是我的代码的第一个(也是有问题的)位:
from bs4 import BeautifulSoup
with open("doc.html", "r") as f:
contents = f.read()
soup = BeautifulSoup(contents, 'lxml')
print(soup.h2)
print(soup.head)
print(soup.li)
Run Code Online (Sandbox Code Playgroud)
这是错误显示:
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-1-4805460879e0> in <module>
3 with open("doc.html", "r") as f:
4
----> 5 contents = f.read()
6
7 soup = BeautifulSoup(contents, 'lxml')
~\Anaconda3\lib\encodings\cp1252.py in …Run Code Online (Sandbox Code Playgroud) '我是刮新的。我想抓取 2018-19 赛季英超联赛结果(赛程、结果、日期),但我很难浏览网站。我得到的只是空列表/[无]。如果你有一个可以分享的解决方案,那将是一个很大的帮助。'
“这就是我试过的。”
'''
import pandas as pd
import requests as uReq
from bs4 import BeautifulSoup
url = uReq.get('https://www.flashscore.com/football/england/premier-league-2018-2019/results/')
soup = BeautifulSoup(url.text, 'html.parser')
divs = soup.find_all('div', attrs={'id': 'live-table'})
Home = []
for div in divs:
anchor = div.find(class_='event__participant event__participant--home')
Home.append(anchor)
print(Home)
Run Code Online (Sandbox Code Playgroud)
'''
我正在尝试从该网站抓取图片和新闻网址。我定义的标签是
root_tag=["div", {"class":"ngp_col ngp_col-bottom-gutter-2 ngp_col-md-6 ngp_col-lg-4"}]
image_tag=["div",{"class":"low-rez-image"},"url"]
news_url=["a",{"":""},"href"]
Run Code Online (Sandbox Code Playgroud)
和 url 是url,我用于抓取网站的代码是。
ua1 = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
ua2 = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome'
headers = {'User-Agent': ua2,
'Accept': 'text/html,application/xhtml+xml,application/xml;' \
'q=0.9,image/webp,*/*;q=0.8'}
session = requests.Session()
response = session.get(url, headers=headers)
webContent = response.content
bs = BeautifulSoup(webContent, 'lxml')
all_tab_data = bs.findAll(root_tag[0], root_tag[1])
result=[]
for div in all_tab_data:
try:
news_url=None
news_url = div.find(news_tag[0], news_tag[1]).get(news_tag[2])
except Exception as e:
news_url= None
try: …Run Code Online (Sandbox Code Playgroud) 我想抓取德国房地产网站 immobilienscout24.de。我想下载给定 URL 的 HTML,然后离线使用 HTML。它不用于商业用途或出版,我也不打算向网站发送垃圾邮件,它仅用于编码练习。我想编写一个 python 工具,自动下载给定 immobilienscout24.de 站点的 HTML。我曾尝试为此使用 beautifulsoup,但是,解析的 HTML 没有显示内容,而是询问我是否是机器人等,这意味着我的网络爬虫被检测到并被阻止(我可以在 Firefox 中访问该站点就好了)。我已经设置了一个引用、一个延迟和一个用户代理。我还能做些什么来避免被检测到(即旋转代理、旋转用户代理、随机点击、其他未被检测到的网页抓取工具...... )?我曾尝试使用我的电话 IP 但得到了相同的结果。GUI webscraping 工具不是一个选项,因为我需要用 python 控制它。如果可能,请提供一些可实现的代码。到目前为止,这是我的代码:
import urllib.request
from bs4 import BeautifulSoup
import requests
import time
import numpy
url = "https://www.immobilienscout24.de/Suche/de/wohnung-mieten?sorting=2#"
req = urllib.request.Request(url, data=None, headers={ 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36' })
req.add_header('Referer', 'https://www.google.de/search?q=immoscout24)
delays = [3, 2, 4, 6, 7, 10, 11, 17]
time.sleep(numpy.random.choice(delays)) # I want to implement delays like this
page …Run Code Online (Sandbox Code Playgroud) 所以我正在从这个网站上抓取 MCQ。我最后想要正确的选择。所有选项共享相同的class='radio-button-click-target'。但正确的选项最后有单选按钮点击目标更正问题。我试过BeautifulSoup webscraping find_all(): 寻找自定义函数的精确匹配解决方案,但现在没有出现任何选项。
import requests
from bs4 import BeautifulSoup
address = 'https://www.ilmkidunya.com/online-test/5th-class-science-english-meduim-mcqs-with-answers?startfrom=0&last=92'
response = requests.get(address)
soup = BeautifulSoup(response.text, 'lxml')
ques_id = soup.find_all('div', class_='q-title')
ques_det = soup.find_all('div', class_='q-desc')
optn_det = soup.find_all('div', class_='choose-answer-block')
for i in range(0, len(ques_id)):
print((ques_id[i].text))
print(str(ques_det[i].text).strip())
options = optn_det[i].find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['radio-button-click-target correctquestions'])
for opn in options:
print(str(opn.text).strip())
print('<----->')
Run Code Online (Sandbox Code Playgroud)
电流输出
Question # 1
The group which belong to invertebrates is.
amphibians
Worms
Reptiles …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用请求模块从网页中抓取公司名称及其相应的链接。
尽管内容非常动态,但我可以注意到它们在window.props.
所以,我想挖出那部分并使用 json 处理它,但我看到\u0022周围的字符而不是引号"。这就是我的意思:
{\u0022firms\u0022: [{\u0022index\u0022: 1, \u0022slug\u0022: \u0022zjjz\u002Datelier\u0022, \u0022name\u0022:
Run Code Online (Sandbox Code Playgroud)
我试过:
import re
import json
import requests
from bs4 import BeautifulSoup
link = 'https://architizer.com/firms/'
with requests.Session() as s:
s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
r = s.get(link)
items = re.findall(r'window.props[^"]+(.*?);',r.text)[0].strip('"').replace('\u0022', '\'')
print(items)
Run Code Online (Sandbox Code Playgroud)
如何使用请求从该网页中抓取不同公司的名称和链接?
所以我基本上试图找到这个 ul 的孩子,但只找到孩子下的元素
所以如果我有这个 html 块
<ul>
<li class = "list_item_1">item 1</li>
<li class = "list_item_2">item 2</li>
<li class = "list_item_3">item 3</li>
<li class = "list_item_4">item 4</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
我想使用 find_all 抓住第二个项目下面的孩子
所以我希望 find_all 的输出是
[<li class = "list_item_3">item 3</li> , <li class = "list_item_4">item 4</li>]
Run Code Online (Sandbox Code Playgroud) beautifulsoup ×10
python ×8
web-scraping ×6
python-3.x ×4
encode ×1
encoding ×1
escaping ×1
graphql ×1
html ×1
lxml ×1
pandas ×1
proxy ×1
selenium ×1